国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

如何在Java Filter 中注入 Service

2019-11-15 01:18:52
字體:
供稿:網(wǎng)友
如何在java Filter 中注入 Service

在項目中遇到一個問題,在 Filter中注入 Serivce失敗,注入的service始終為null。如下所示:

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

上面的 usersService 會報空指針異常。

解決方法

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {        HttpServletRequest req = (HttpServletRequest)request;        HttpServletResponse resp = (HttpServletResponse)response;  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);

這樣就行了。

方法二

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

相關(guān)原理:

1. 如何獲取 ServletContext

1)在javax.servlet.Filter中直接獲取 ServletContext context = config.getServletContext();2)在HttpServlet中直接獲取this.getServletContext()3)在其他方法中,通過HttpServletRequest獲得request.getSession().getServletContext();

2. WebApplicationContext 與 ServletContext (轉(zhuǎn)自:http://blessht.VEvb.com/blog/2121845):

Spring的 ContextLoaderListener是一個實現(xiàn)了ServletContextListener接口的監(jiān)聽器,在啟動項目時會觸發(fā)contextInitialized方法(該方法主要完成ApplicationContext對象的創(chuàng)建),在關(guān)閉項目時會觸發(fā)contextDestroyed方法(該方法會執(zhí)行ApplicationContext清理操作)。

ConextLoaderListener加載Spring上下文的過程

①啟動項目時觸發(fā)contextInitialized方法,該方法就做一件事:通過父類contextLoader的initWebApplicationContext方法創(chuàng)建Spring上下文對象。

②initWebApplicationContext方法做了三件事:創(chuàng)建 WebApplicationContext;加載對應(yīng)的Spring文件創(chuàng)建里面的Bean實例;將WebApplicationContext放入 ServletContext(就是Java Web的全局變量)中

③createWebApplicationContext創(chuàng)建上下文對象,支持用戶自定義的上下文對象,但必須繼承自ConfigurableWebApplicationContext,而Spring MVC默認(rèn)使用ConfigurableWebApplicationContext作為ApplicationContext(它僅僅是一個接口)的實 現(xiàn)。

④configureAndRefreshWebApplicationContext方法用 于封裝ApplicationContext數(shù)據(jù)并且初始化所有相關(guān)Bean對象。它會從web.xml中讀取名為 contextConfigLocation的配置,這就是spring xml數(shù)據(jù)源設(shè)置,然后放到ApplicationContext中,最后調(diào)用傳說中的refresh方法執(zhí)行所有Java對象的創(chuàng)建。

⑤完成ApplicationContext創(chuàng)建之后就是將其放入ServletContext中,注意它存儲的key值常量。

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> 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);                return;            }else{                if(req.getSession().getAttribute(CommonConstants.SESSION_KEY_USER) == null){ // 未登錄                    String llFlag = (String) req.getSession().getAttribute("LLFlag");                    if(llFlag != null && llFlag.equals("1")){    // 處理游客瀏覽                        chain.doFilter(request, response);                        return;                    }                                      // ... ...// 3. 從騰訊服務(wù)器去獲得微信的 openid ,                    req.getRequestDispatcher("/weixin_gate.html").forward(request, response);                    return;                }else{    // 已經(jīng)登錄                    // 4. 已經(jīng)登錄時的處理                                        chain.doFilter(request, response);                     return;                }            }                    }else{    // 非微信瀏覽器            chain.doFilter(request, response);        }    }}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 通江县| 北流市| 陕西省| 石阡县| 安阳县| 淮阳县| 乌兰察布市| 阿拉善盟| 娱乐| 夏津县| 清镇市| 南皮县| 特克斯县| 阜新| 花莲市| 新竹市| 阿瓦提县| 滦南县| 长治县| 旬邑县| 威信县| 郑州市| 米泉市| 中江县| 静乐县| 乳山市| 蒙自县| 乌鲁木齐县| 奈曼旗| 古丈县| 玉门市| 涞水县| 宜昌市| 重庆市| 江阴市| 延吉市| 彩票| 玉林市| 壶关县| 奉新县| 高唐县|