How to inject Service in Java 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
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).
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
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);
}}}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics
![How to solve the '[Vue warn]: Failed to resolve filter' error](https://img.php.cn/upload/article/000/887/227/169243040583797.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
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

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

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

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

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

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
