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