使用的工具類
package com.fltd.tourism.util; import java.util.Locale; import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; } /** * 獲取applicationContext對象 * * @return */ public static ApplicationContext getApplicationContext() { return applicationContext; } @SuppressWarnings("unchecked") public static <T> T getBean(String name) { return (T) applicationContext.getBean(name); } public static <T> T getBean(Class<T> clazz) { System.out.println(applicationContext); return applicationContext.getBean(clazz); } /** * 根據bean的id來查找對�? * * @param id * @return */ @SuppressWarnings("unchecked") public static <T> T getBeanById(String id) { return (T) applicationContext.getBean(id); } /** * 根據bean的class來查找對�? * * @param c * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T getBeanByClass(Class c) { return (T) applicationContext.getBean(c); } /** * 根據bean的class來查找所有的對象(包括子類) * * @param c * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Map getBeansByClass(Class c) { return applicationContext.getBeansOfType(c); } public static String getMessage(String key) { return applicationContext.getMessage(key, null, Locale.getDefault()); } }
使用方法:
SpringContextUtil.getBean(xxxService.class).xxxmethod();
或者使用
在項目中遇到一個問題,在 Filter中注入 Serivce失敗,注入的service始終為null。如下所示:
1 public class WeiXinFilter implements Filter{ 2 3 @Autowired 4 private UsersService usersService; 5 6 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 7 HttpServletRequest req = (HttpServletRequest)request; 8 HttpServletResponse resp = (HttpServletResponse)response; 9 Users users = this.usersService.queryByOpenid(openid); 10 }
上面的 usersService 會報空指針異常。
解決方法一:
1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 2 HttpServletRequest req = (HttpServletRequest)request; 3 HttpServletResponse resp = (HttpServletResponse)response; 4 ServletContext sc = req.getSession().getServletContext(); 5 XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc); 6 7 if(cxt != null && cxt.getBean("usersService") != null && usersService == null) 8 usersService = (UsersService) cxt.getBean("usersService"); 9 10 Users users = this.usersService.queryByOpenid(openid);
解決方法二:
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); if(cxt != null && cxt.getBean("usersService") != null && usersService == null) usersService = (UsersService) cxt.getBean("usersService"); }
相關原理:
1. 如何獲取 ServletContext:
1)在javax.servlet.Filter中直接獲取
ServletContext context = config.getServletContext();
2)在HttpServlet中直接獲取
this.getServletContext()
3)在其他方法中,通過HttpServletRequest獲得
request.getSession().getServletContext();
2. WebApplicationContext 與 ServletContext (轉自:http://blessht.iteye.com/blog/2121845):
Spring的 ContextLoaderListener是一個實現了ServletContextListener接口的監聽器,在啟動項目時會觸發contextInitialized方法(該方法主要完成ApplicationContext對象的創建),在關閉項目時會觸發contextDestroyed方法(該方法會執行ApplicationContext清理操作)。
ConextLoaderListener加載Spring上下文的過程
①啟動項目時觸發contextInitialized方法,該方法就做一件事:通過父類contextLoader的initWebApplicationContext方法創建Spring上下文對象。
②initWebApplicationContext方法做了三件事:創建 WebApplicationContext;加載對應的Spring文件創建里面的Bean實例;將WebApplicationContext放入 ServletContext(就是Java Web的全局變量)中。
③createWebApplicationContext創建上下文對象,支持用戶自定義的上下文對象,但必須繼承自ConfigurableWebApplicationContext,而Spring MVC默認使用ConfigurableWebApplicationContext作為ApplicationContext(它僅僅是一個接口)的實 現。
④configureAndRefreshWebApplicationContext方法用 於封裝ApplicationContext數據並且初始化所有相關Bean對象。它會從web.xml中讀取名為 contextConfigLocation的配置,這就是spring xml數據源設置,然后放到ApplicationContext中,最后調用傳說中的refresh方法執行所有Java對象的創建。
⑤完成ApplicationContext創建之后就是將其放入ServletContext中,注意它存儲的key值常量。
解決方法三:
直接使用spring mvc中的HandlerInterceptor或者HandlerInterceptorAdapter 來替換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 } }
配置攔截路徑:
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="net.xxxx.interceptor.WeiXinInterceptor" /> </mvc:interceptor> </mvc:interceptors>
Filter 中注入 Service 的示例:
1 public class WeiXinFilter implements Filter{ 2 private UsersService usersService; 3 public void init(FilterConfig fConfig) throws ServletException {} 4 public WeiXinFilter() {} 5 public void destroy() {} 6 7 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 8 HttpServletRequest req = (HttpServletRequest)request; 9 HttpServletResponse resp = (HttpServletResponse)response; 10 11 String userAgent = req.getHeader("user-agent"); 12 if(userAgent != null && userAgent.toLowerCase().indexOf("micromessenger") != -1){ // 微信瀏覽器 13 String servletPath = req.getServletPath(); 14 String requestURL = req.getRequestURL().toString(); 15 String queryString = req.getQueryString(); 16 17 if(queryString != null){ 18 if(requestURL.indexOf("mtzs.html") !=-1 && queryString.indexOf("LLFlag")!=-1){ 19 req.getSession().setAttribute("LLFlag", "1"); 20 chain.doFilter(request, response); 21 return; 22 } 23 } 24 25 String openidDES = CookieUtil.getValueByName("openid", req); 26 String openid = null; 27 if(StringUtils.isNotBlank(openidDES)){ 28 try { 29 openid = DesUtil.decrypt(openidDES, "rxxxxxxxxxde"); // 解密獲得openid 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } 33 } 34 // ... ... 35 String[] pathArray = {"/weixin/enterAppFromWeiXin.json", "/weixin/getWeiXinUserInfo.json", 36 "/weixin/getAccessTokenAndOpenid.json", "/sendRegCode.json", "/register.json", 37 "/login.json", "/logon.json", "/dump.json", "/queryInfo.json"}; 38 List<String> pathList = Arrays.asList(pathArray); 39 40 String loginSuccessUrl = req.getParameter("path"); 41 String fullLoginSuccessUrl = "http://www.axxxxxxx.cn/pc/"; 42 if(requestURL.indexOf("weixin_gate.html") != -1){ 43 req.getSession().setAttribute("loginSuccessUrl", loginSuccessUrl); 44 // ... ... 45 } 46 ServletContext sc = req.getSession().getServletContext(); 47 XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc); 48 49 if(cxt != null && cxt.getBean("usersService") != null && usersService == null) 50 usersService = (UsersService) cxt.getBean("usersService"); 51 52 Users users = this.usersService.queryByOpenid(openid); 53 // ... ... 54 if(pathList.contains(servletPath)){ // pathList 中的訪問路徑直接 pass 55 chain.doFilter(request, response); 56 return; 57 }else{ 58 if(req.getSession().getAttribute(CommonConstants.SESSION_KEY_USER) == null){ // 未登錄 59 String llFlag = (String) req.getSession().getAttribute("LLFlag"); 60 if(llFlag != null && llFlag.equals("1")){ // 處理游客瀏覽 61 chain.doFilter(request, response); 62 return; 63 } 64 // ... ...// 3. 從騰訊服務器去獲得微信的 openid , 65 req.getRequestDispatcher("/weixin_gate.html").forward(request, response); 66 return; 67 }else{ // 已經登錄 68 // 4. 已經登錄時的處理 69 chain.doFilter(request, response); 70 return; 71 } 72 } 73 }else{ // 非微信瀏覽器 74 chain.doFilter(request, response); 75 } 76 } 77 78 }