Home 类库下载 java类库 How to inject Service in Java Filter

How to inject Service in Java Filter

Nov 26, 2016 am 09:10 AM
filter

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








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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the '[Vue warn]: Failed to resolve filter' error How to solve the '[Vue warn]: Failed to resolve filter' error Aug 19, 2023 pm 03:33 PM

Methods to solve the "[Vuewarn]:Failedtoresolvefilter" error During the development process using Vue, we sometimes encounter an error message: "[Vuewarn]:Failedtoresolvefilter". This error message usually occurs when we use an undefined filter in the template. This article explains how to resolve this error and gives corresponding code examples. When we are in Vue

How to integrate Filter in SpringBoot2 How to integrate Filter in SpringBoot2 May 16, 2023 pm 02:46 PM

First define a Filter for unified access URL interception. The code is as follows: publicclassUrlFilterimplementsFilter{privateLoggerlog=LoggerFactory.getLogger(UrlFilter.class);@OverridepublicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{H

What is the principle and registration method of filter in Springboot What is the principle and registration method of filter in Springboot May 11, 2023 pm 08:28 PM

1. Filter First look at the location of the filter of the web server. Filter is a chain connected before and after. After the previous processing is completed, it is passed to the next filter for processing. 1.1Filter interface definition publicinterfaceFilter{//Initialization method, only executed once in the entire life cycle. //Filtering services cannot be provided until the init method is successfully executed (failure such as throwing an exception, etc.). //The parameter FilterConfig is used to obtain the initialization parameter publicvoidinit(FilterConfigfilterConfig)throwsServletException;//

Detailed explanation of CSS blur properties: filter and backdrop-filter Detailed explanation of CSS blur properties: filter and backdrop-filter Oct 20, 2023 pm 04:48 PM

Detailed explanation of CSS fuzzy attributes: filter and background-filter Introduction: When designing web pages, we often need some special effects to increase the visual appeal of the page. The blur effect is one of the common special effects. CSS provides two blur attributes: filter and background-filter, which are used to blur element content and background content respectively. This article explains these two properties in detail and provides some concrete code examples. 1. filter

How to filter in java How to filter in java Apr 18, 2023 pm 11:04 PM

Note 1. If the Lambda parameter generates a true value, the filter (Lambda that can generate a boolean result) will generate an element; 2. When false is generated, this element will no longer be used. Example to create a List collection: ListstringCollection=newArrayList();stringCollection.add("ddd2");stringCollection.add("aaa2");stringCollection.add("bbb1");stringC

CSS visual property analysis: box-shadow, text-shadow and filter CSS visual property analysis: box-shadow, text-shadow and filter Oct 20, 2023 pm 12:51 PM

Analysis of CSS visual properties: box-shadow, text-shadow and filter Introduction: In web design and development, CSS can be used to add various visual effects to elements. This article will focus on the three important properties of box-shadow, text-shadow and filter in CSS, including their usage and effect display. Below we analyze these three properties in detail. 1. box-shadow (box shadow) box-shado

Optional class in Java 8: How to filter possibly null values ​​using filter() method Optional class in Java 8: How to filter possibly null values ​​using filter() method Aug 01, 2023 pm 05:27 PM

Optional class in Java8: How to use the filter() method to filter possibly null values ​​In Java8, the Optional class is a very useful tool that allows us to better handle possibly null values ​​and avoid the occurrence of NullPointerException. The Optional class provides many methods to manipulate potential null values, one of the important methods is filter(). The function of the filter() method is that if Option

How to use filters to format and process data in Vue How to use filters to format and process data in Vue Oct 15, 2023 pm 03:50 PM

Use filters to format and process data in Vue In Vue, we can format and process data by using filters. Filter is a function that can be called directly in the template. It can process the data to be displayed and return the processed results. In this article, we will introduce how to use filters to format and process data, and provide specific code examples. Register filter In the Vue instance, we need to register a filter first so that it can be used in the model

See all articles