在项目中遇到一个问题,在 Filter中注入 Serivce失败,注入的service始终为null。如下所示:

 public class WeiXinFilter implements Filter{

     @Autowired
private UsersService usersService; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
     Users users = this.usersService.queryByOpenid(openid);
}

上面的 usersService 会报空指针异常。

解决方法一

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
ServletContext sc = req.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc); if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
usersService = (UsersService) cxt.getBean("usersService"); Users users = this.usersService.queryByOpenid(openid);

解决方法二

public class WeiXinFilter implements Filter{

    private UsersService usersService;

    public void init(FilterConfig fConfig) throws ServletException {
ServletContext sc = fConfig.getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc); if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
usersService = (UsersService) cxt.getBean("usersService");
}

相关原理:

1. 如何获取 ServletContext

1)在javax.servlet.Filter中直接获取
ServletContext context = config.getServletContext();

2)在HttpServlet中直接获取
this.getServletContext()

3)在其他方法中,通过HttpServletRequest获得
request.getSession().getServletContext();

2. WebApplicationContext 与 ServletContext (转自:http://blessht.iteye.com/blog/2121845):

Spring的 ContextLoaderListener是一个实现了ServletContextListener接口的监听器,在启动项目时会触发contextInitialized方法(该方法主要完成ApplicationContext对象的创建),在关闭项目时会触发contextDestroyed方法(该方法会执行ApplicationContext清理操作)。

ConextLoaderListener加载Spring上下文的过程

①启动项目时触发contextInitialized方法,该方法就做一件事:通过父类contextLoader的initWebApplicationContext方法创建Spring上下文对象。

②initWebApplicationContext方法做了三件事:创建 WebApplicationContext;加载对应的Spring文件创建里面的Bean实例;将WebApplicationContext放入 ServletContext(就是Java Web的全局变量)中

③createWebApplicationContext创建上下文对象,支持用户自定义的上下文对象,但必须继承自ConfigurableWebApplicationContext,而Spring MVC默认使用ConfigurableWebApplicationContext作为ApplicationContext(它仅仅是一个接口)的实 现。

④configureAndRefreshWebApplicationContext方法用 于封装ApplicationContext数据并且初始化所有相关Bean对象。它会从web.xml中读取名为 contextConfigLocation的配置,这就是spring xml数据源设置,然后放到ApplicationContext中,最后调用传说中的refresh方法执行所有Java对象的创建。

⑤完成ApplicationContext创建之后就是将其放入ServletContext中,注意它存储的key值常量。

解决方法三

直接使用spring mvc中的HandlerInterceptor或者HandlerInterceptorAdapter 来替换Filter:

public class WeiXinInterceptor implements HandlerInterceptor {
@Autowired
private UsersService usersService; @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// TODO Auto-generated method stub
return false;
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
// TODO Auto-generated method stub } @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// TODO Auto-generated method stub }
}

配置拦截路径:

    <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="net.xxxx.interceptor.WeiXinInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

Filter 中注入 Service 的示例:

 public class WeiXinFilter implements Filter{
private UsersService usersService;
public void init(FilterConfig fConfig) throws ServletException {}
public WeiXinFilter() {}
public void destroy() {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response; String userAgent = req.getHeader("user-agent");
if(userAgent != null && userAgent.toLowerCase().indexOf("micromessenger") != -1){ // 微信浏览器
String servletPath = req.getServletPath();
String requestURL = req.getRequestURL().toString();
String queryString = req.getQueryString(); if(queryString != null){
if(requestURL.indexOf("mtzs.html") !=-1 && queryString.indexOf("LLFlag")!=-1){
req.getSession().setAttribute("LLFlag", "1");
chain.doFilter(request, response);
return;
}
} String openidDES = CookieUtil.getValueByName("openid", req);
String openid = null;
if(StringUtils.isNotBlank(openidDES)){
try {
openid = DesUtil.decrypt(openidDES, "rxxxxxxxxxde"); // 解密获得openid
} catch (Exception e) {
e.printStackTrace();
}
}
// ... ...
String[] pathArray = {"/weixin/enterAppFromWeiXin.json", "/weixin/getWeiXinUserInfo.json",
"/weixin/getAccessTokenAndOpenid.json", "/sendRegCode.json", "/register.json",
"/login.json", "/logon.json", "/dump.json", "/queryInfo.json"};
List<String> pathList = Arrays.asList(pathArray); String loginSuccessUrl = req.getParameter("path");
String fullLoginSuccessUrl = "http://www.axxxxxxx.cn/pc/";
if(requestURL.indexOf("weixin_gate.html") != -1){
req.getSession().setAttribute("loginSuccessUrl", loginSuccessUrl);
          // ... ...
}
ServletContext sc = req.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc); if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
usersService = (UsersService) cxt.getBean("usersService"); Users users = this.usersService.queryByOpenid(openid);
// ... ...
if(pathList.contains(servletPath)){ // pathList 中的访问路径直接 pass
chain.doFilter(request, response);
return;
}else{
if(req.getSession().getAttribute(CommonConstants.SESSION_KEY_USER) == null){ // 未登录
String llFlag = (String) req.getSession().getAttribute("LLFlag");
if(llFlag != null && llFlag.equals("1")){ // 处理游客浏览
chain.doFilter(request, response);
return;
}
// ... ...// 3. 从腾讯服务器去获得微信的 openid ,
req.getRequestDispatcher("/weixin_gate.html").forward(request, response);
return;
}else{ // 已经登录
// 4. 已经登录时的处理
chain.doFilter(request, response);
return;
}
}
}else{ // 非微信浏览器
chain.doFilter(request, response);
}
} }

在Java filter中调用service层方法的更多相关文章

  1. ssh框架,工具类调用service层方法

    解决方法: @Component//声明为spring组件 public class CopyFileUtil{ @Autowired private DataFileManager dataFile ...

  2. 如何在Java Filter 中注入 Service

    在项目中遇到一个问题,在 Filter中注入 Serivce失败,注入的service始终为null.如下所示: public class WeiXinFilter implements Filter ...

  3. SpringBoot在自定义类中调用service层等Spring其他层

    解决方案: 1.上代码 @Component public class ServerHandler extends IoHandlerAdapter { @Autowired protected He ...

  4. Spring框架中,在工具类或者普通Java类中调用service或dao

    spring注解的作用: 1.spring作用在类上的注解有@Component.@Responsity.@Service以及@Controller:而@Autowired和@Resource是用来修 ...

  5. ssh框架中,工具类调用service层方法(参考https://www.cnblogs.com/l412382979/p/8526945.html)

    代码如下: package common.dataService; import javax.annotation.PostConstruct; import org.springframework. ...

  6. TimerTask的run()方法里面如何调用service层里面的方法

    在java的spring框架中,用Timer和TimerTask来实现定时任务,有时我们要在TimerTask的子类的重写run方法里,调用service层的方法. 但是不管是spring.xml配置 ...

  7. 如何在Java的Filter中注入Service???

    今天在做用户使用cookie自动登录的时候,发现在LoginFilter中读取到cookie以后要进行查询数据库然后进行用户名和密码的比对,查询数据库肯定要用到Service和Dao,一开始我以为在s ...

  8. Spring MVC普通类或工具类中调用service报空空指针的解决办法(调用service报java.lang.NullPointerException)

    当我们在非Controller类中应用service的方法是会报空指针,如图: 这是因为Spring MVC普通类或工具类中调用service报空null的解决办法(调用service报java.la ...

  9. Java程序中调用Python脚本的方法

    在程序开发中,有时候需要Java程序中调用相关Python脚本,以下内容记录了先关步骤和可能出现问题的解决办法. 1.在Eclipse中新建Maven工程: 2.pom.xml文件中添加如下依赖包之后 ...

随机推荐

  1. php 资源

    ThinkPHP http://www.thinkphp.cn/ 小案例 http://www.helloweba.com/php.html Github上的PHP资源汇总大全 http://www. ...

  2. PHP5.5.13 + Apache2.4.7安装配置流程详解

    ---恢复内容开始--- 自学PHP的这段时间里,真是倍感辛酸,相信广大的菜鸟们应该很我感同身受吧,在查阅了网上和众多数资料后,总结出来想当比较全面的安装方法,拿出来与广大的编程爱好者一起分享哈. 首 ...

  3. web开发字符乱码问题

    java动态网页后台乱码问题总结 乱码可能出现的几块地方: 首先是浏览器和html之间采用的编码不一致 解决办法: 修改浏览器的编码格式 修改html页面的编码格式: <meta http-eq ...

  4. shell中三种引号的用法

    1.单引号 所见即所得 例如:var=123 var2='${var}123' echo var2 var2结果为${var}123 2.双引号 输出引号中的内容,若存在命令.变量等,会先执行命令解析 ...

  5. 各种文件的mime类型

    扩展名:abs MIME类型:audio/x-mpeg 扩展名:ai MIME类型:application/postscript 扩展名:aif MIME类型:audio/x-aiff 扩展名:aif ...

  6. contiki-rtimer

    struct rtimer { rtimer_clock_t time; rtimer_callback_t func; void *ptr; }; typedef unsigned short rt ...

  7. Sprint2(12.6)

    Sprint1第二阶段 1.类名:软件工程-第二阶段 方案一:此方案操作界面只有前台.厨房 (1)前台:用户到前台点餐,服务员操作界面,勾选客人所在桌号(不可重复勾选),并输入所选菜品,可增.删.改所 ...

  8. activitygroup下的activity不回调onactivityresult的解决方法

    就是activitygroup下的子activity启动第三方activity的时候需要通过getparent的startactivityforresult方法来启动.getparent其实就是这个a ...

  9. D​e​p​l​o​y​m​e​n​t​ ​f​a​i​l​u​r​e​ ​o​n​ ​T​o​m​c​a​t​ ​6​.​x​.​ ​C​o​u​l​d​ ​n​o​t​ ​c​o​p​y​ ​a​l​l​ ​r​e​s​o​u​r​c​e​s​ ​t​o

    在myeclipse总部署项目,一直有问题,提示如下的错误,经过研究在网上需求帮助,解决方案如下: Deployment failure on Tomcat  6.x. Could not copy  ...

  10. JavaScipt 数据交互

    标准的w3c直接提供了XMLHttpRequest方法,我们主要站在设计的角度来理解,如何设计出低耦合高内聚的代码jquery对Ajax的处理主要体现在对浏览器兼容,数据的处理过滤以及各种事件的封装上 ...