在專案中遇到一個問題,在 Filter中註入 Serivce失敗,注入的service總是為null。如下圖所示:
public class WeiXinFilter implements Filter{
@Autowired
private UsersService usService; terChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request ;
HttpServletResponse resp = (HttpServletResponse)response;
Users users = this.usService.queryByOpenid(p報空指針異常。
解決方法一:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
questHttpServletResponse resp = (HttpServletResponse)response; ServletContext sc = req .getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc); 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; ServletContext sc = fConfig.getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils. getWebApplicationContext(sc);
if(cxt != null && cxt.getBean("usersService") != null &. ersService");
}
相關原理:
1. 如何取得ServletContext:
1)在javax.servlet.Filter中直接取得
ServletContext context = config.getServletContext(); )
3)其他方法中,透過HttpServletRequest取得
request.getSession().getServletContext();
2. WebApplicationContext 與ServletContext (轉自:http://blog/itep.
Spring的ContextLoaderListener是一個實作了ServletContextListener介面的監聽器,在啟動專案時會觸發contextInitialized方法(方法主要完成ApplicationContext物件的建立),在關閉專案時會觸發contextDestroyed方法(該方法清理操作) 。
ConextLoaderListener載入Spring上下文的過程
⑤完成ApplicationContext建立之後就是將其放入ServletContext中,注意它儲存的key值常數。
方法三:
直接使用spring mvc中的HandlerInterceptor或HandlerInterceptorAdapter 來替換Filter:
公用類別WeiXinInterceptor 實作了HandlerInterceptor {
@Autowired private UsersService usersService;
Serdlep. Object handler) throws Exception { // TODO 自動產生的方法存根
return false;
}
@Override public void postHandle( HttpServletRequest 請求、HttpServletResponse 回應、物件處理程序, ModelAndView modelAndView) DO
}
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TO DO 自動產生的方法存根
}
}
Filter 中註入服務的範例:
public class WeiXinFilter 實作 Filter{
private UsersService usersService;
public void init(FilterConfig fConfig) throws ServletException {} public WeiXinFilter() {} public void destroy() {} 1public void doFilter(Servlet , ServletException {
HttpServletRequest req = (HttpServletRequest)請求;
HttpServletResponse resp = (HttpServletResponse)response;
StringHeader = regent getuserAgent = re if(userAgent != null && userAgent.toLowerCase().indexOf("micromessenger") != -1){ // 微信瀏覽器
= req.getRequestURL(). toString();
String queryString = req.getQueryString();
if(queryString != null){ if(requestURL.indexOf("mtzs.html") !=-1 &queo lag. req.getSession().setAttribute(" LLFlag", "1");
chain.doFilter(請求, 回應); return;
}
}
String openid = null; if(StringUtils.isNotBlank(openidDES)){ 嘗試 {
xxx7id = Despp.pid = DesHtil.xxx(openopenpde); // 取得openid
} catch (Exception e) {
}
/ / ... ...
String[] pathArray = {"/weixin. weixin 「/login.json」、「/logon.json」、「/dump.json 」 ” json", "/queryInfo.json"};
List
String fullLoginSuccessUrl = 「http: // /www.axxxxxxx.cn/pc/"; if(requestURL.indexOf("weixin_gate.html") != -1){
);
❤️❤️ ❤️/ / ... ...
}
ServletContext sc = 請求。 sc);
if(cxt != null && cxt. getBean( "usersService") != null && usersService == null)
usersService = (UsersService) cxt.getBean("usersService");
.
// ... .. . if(pathList.contains(servletPath)){ //路徑清單中的存取路徑直接通行證明
chain.doFilter(request, response); return;
}else{ _USER) == null){ // 未登入
String llFlag = (String) req.getSession() .getAttribute("LLFlag"); if(llFlag != null && llFlag.equals("1")){ Filter(request, response); return;
// ... . ..// 3. 從騰訊伺服器去取得微信的openid ,
req.getRequestDispatcher("/weixin_gate.html request, response
}else{ // 已登入 //登錄時的處理
chain.doFilter(request, response);
return;
}
}
}else{ // 非微信瀏覽器 chain.doFilter(request, response);
}
}}