0

0

如何在Java Filter 中注入 Service

巴扎黑

巴扎黑

发布时间:2016-11-26 09:10:38

|

2031人浏览过

|

来源于php中文网

原创

在项目中遇到一个问题,在 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 会报空指针异常。

立即学习Java免费学习笔记(深入)”;

解决方法一:

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清理操作)。

Android 开发者指南 第一部分:入门
Android 开发者指南 第一部分:入门

Android文档-开发者指南-第一部分:入门-中英文对照版 Android提供了丰富的应用程序框架,它允许您在Java语言环境中构建移动设备的创新应用程序和游戏。在左侧导航中列出的文档提供了有关如何使用Android的各种API来构建应用程序的详细信息。第一部分:Introduction(入门) 0、Introduction to Android(引进到Android) 1、Application Fundamentals(应用程序基础) 2、Device Compatibility(设备兼容性) 3、

下载

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        
   }
}

配置拦截路径:

   
       
           
           
       
   
   

 

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 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速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

37

2026.01.14

php与html混编教程大全
php与html混编教程大全

本专题整合了php和html混编相关教程,阅读专题下面的文章了解更多详细内容。

19

2026.01.13

PHP 高性能
PHP 高性能

本专题整合了PHP高性能相关教程大全,阅读专题下面的文章了解更多详细内容。

37

2026.01.13

MySQL数据库报错常见问题及解决方法大全
MySQL数据库报错常见问题及解决方法大全

本专题整合了MySQL数据库报错常见问题及解决方法,阅读专题下面的文章了解更多详细内容。

19

2026.01.13

PHP 文件上传
PHP 文件上传

本专题整合了PHP实现文件上传相关教程,阅读专题下面的文章了解更多详细内容。

16

2026.01.13

PHP缓存策略教程大全
PHP缓存策略教程大全

本专题整合了PHP缓存相关教程,阅读专题下面的文章了解更多详细内容。

6

2026.01.13

jQuery 正则表达式相关教程
jQuery 正则表达式相关教程

本专题整合了jQuery正则表达式相关教程大全,阅读专题下面的文章了解更多详细内容。

3

2026.01.13

交互式图表和动态图表教程汇总
交互式图表和动态图表教程汇总

本专题整合了交互式图表和动态图表的相关内容,阅读专题下面的文章了解更多详细内容。

45

2026.01.13

nginx配置文件详细教程
nginx配置文件详细教程

本专题整合了nginx配置文件相关教程详细汇总,阅读专题下面的文章了解更多详细内容。

9

2026.01.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
全面解析Java注解
全面解析Java注解

共12课时 | 2.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号