Home > 类库下载 > java类库 > body text

How to inject Service in Java Filter

巴扎黑
Release: 2016-11-26 09:10:38
Original
1829 people have browsed it

I encountered a problem in the project. Injecting Serivce into Filter failed and the injected service was always null. As shown below:

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

The above usersService will report a null pointer exception.

Solution 1:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
 HttpServletRequest req = (HttpServletRequest)request;
 HttpServletRe sponse resp = (HttpServletResponse)response; ServletContext sc = req .getSession().getServletContext(); = null && usersService == null)
UsersService = (Usersservice) cxt.getBean ("UsersSservice");

Users used = this.usersservice.querybyopenid (openid);

Method 2:

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);                                                                                                                                                                                               getBean ('); }


Related principles:

1. How to get ServletContext:

1) Get it directly in javax.servlet.Filter
ServletContext context = config.getServletContext();

2) Get it directly in HttpServlet

this.getServletContext( )

3) In other methods, obtain

request.getSession().getServletContext();

2. WebApplicationContext and ServletContext (reprinted from: http://blessht.iteye.com/blog/2121845) through HttpServletRequest:

Spring's ContextLoaderListener is a listener that implements the ServletContextListener interface. When starting the project, the contextInitialized method will be triggered (this method mainly completes the creation of the ApplicationContext object). When the project is closed, the contextDestroyed method will be triggered (this method will perform the ApplicationContext cleanup operation). .

The process of loading the Spring context by ConextLoaderListener

①The contextInitialized method is triggered when starting the project. This method does one thing: creates a Spring context object through the initWebApplicationContext method of the parent class contextLoader.

②The initWebApplicationContext method does three things: creates a WebApplicationContext; loads the corresponding Spring file to create the Bean instance inside; and puts the WebApplicationContext into the ServletContext (which is the global variable of Java Web).

③createWebApplicationContext creates a context object and supports user-defined context objects, but they must inherit from ConfigurableWebApplicationContext, and Spring MVC uses ConfigurableWebApplicationContext as the implementation of ApplicationContext (it is just an interface) by default.

④configureAndRefreshWebApplicationContext method is used to encapsulate ApplicationContext data and initialize all related Bean objects. It will read the configuration named contextConfigLocation from web.xml, which is the spring xml data source setting, then put it into the ApplicationContext, and finally call the legendary refresh method to perform the creation of all Java objects.

⑤After completing the creation of the ApplicationContext, put it into the ServletContext and pay attention to the key value constant it stores.

Method 3:

Directly use HandlerInterceptor or HandlerInterceptorAdapter in spring mvc to replace 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);                                                                                                                                                                String llFlag = (String) req.getSession() .getAttribute("LLFlag");                    if(llFlag != null && llFlag.equals("1")){                                                                                                                                                     return;
                                                                                                     ..// 3. Get WeChat’s openid from Tencent server ,
                                                                                                                                                                                                                                                                             // Already logged in                       // 4. Already Treatment when logging in a chain.dofilter (request, response);
Return;
}}} else {// non -WeChat browser chain.dofilter (request, response);
}}}








Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template