搜尋
首頁类库下载java类库如何在Java Filter 中註入 Service

在專案中遇到一個問題,在 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 {

quest

       HttpServletResponse 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上下文的過程

①啟動專案時觸發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:

公用類別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;路徑列表= Arrays.asList(路徑通道);          
           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);
       }
   }}


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中