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

如何在Java Filter 中註入 Service

Nov 26, 2016 am 09:10 AM
filter

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

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

解決「[Vue warn]: Failed to resolve filter」錯誤的方法 解決「[Vue warn]: Failed to resolve filter」錯誤的方法 Aug 19, 2023 pm 03:33 PM

解決「[Vuewarn]:Failedtoresolvefilter」錯誤的方法在使用Vue進行開發的過程中,我們有時會遇到一個錯誤提示:「[Vuewarn]:Failedtoresolvefilter」。這個錯誤提示通常出現在我們在模板中使用了一個未定義的過濾器的情況下。本文將介紹如何解決這個錯誤並給出相應的程式碼範例。當我們在Vue的

怎麼在SpringBoot2中整合Filter 怎麼在SpringBoot2中整合Filter May 16, 2023 pm 02:46 PM

先定義一個統一存取URL攔截的Filter。程式碼如下:publicclassUrlFilterimplementsFilter{privateLoggerlog=LoggerFactory.getLogger(UrlFilter.class);@OverridepublicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,

Springboot中filter的原理與註冊方法是什麼 Springboot中filter的原理與註冊方法是什麼 May 11, 2023 pm 08:28 PM

1.filter先看下web伺服器的filter所處的位置。 filter是一個前後連接的鏈,前面處理完成之後傳遞給下一個filter處理。 1.1filter的介面定義publicinterfaceFilter{//初始化方法,整個生命週期只執行一次。 //在init方法成功(失敗如拋異常等)執行完前,無法提供過濾服務。 //參數FilterConfig用於取得初始化參數publicvoidinit(FilterConfigfilterConfig)throwsServletException;//

CSS 模糊屬性詳解:filter 與 backdrop-filter CSS 模糊屬性詳解:filter 與 backdrop-filter Oct 20, 2023 pm 04:48 PM

CSS模糊屬性詳解:filter和backdrop-filter導語:在設計網頁時,我們常常需要一些特效來增加頁面的視覺吸引力。而模糊效果是其中一種常見的特效之一。 CSS提供了兩種模糊屬性:filter和backdrop-filter,它們分別用於對元素內容以及背景內容進行模糊處理。本文將詳細介紹這兩個屬性,並提供一些具體的程式碼範例。一、filt

Filter在java中如何過濾 Filter在java中如何過濾 Apr 18, 2023 pm 11:04 PM

說明1、如果Lambda參數產生true值,則filter(能夠產生boolean結果的Lambda)將產生元素;2、產生false時,就不再使用此元素。實例建立一個List集合:ListstringCollection=newArrayList();stringCollection.add("ddd2");stringCollection.add("aaa2");stringCollection.add("bbb1");stringC

CSS 視覺屬性解析:box-shadow,text-shadow 和 filter CSS 視覺屬性解析:box-shadow,text-shadow 和 filter Oct 20, 2023 pm 12:51 PM

CSS視覺屬性解析:box-shadow,text-shadow和filter引言:在網頁設計和開發中,使用CSS可以為元素添加各種視覺效果。本文將重點放在CSS中的box-shadow,text-shadow和filter這三個重要屬性,包括其使用方法和效果展示。下面我們分別詳細解析這三個屬性。一、box-shadow(盒子陰影)box-shado

Java 8中的Optional類別:如何使用filter()方法過濾可能為空的值 Java 8中的Optional類別:如何使用filter()方法過濾可能為空的值 Aug 01, 2023 pm 05:27 PM

Java8中的Optional類別:如何使用filter()方法過濾可能為空的值在Java8中,Optional類別是一個非常有用的工具,它允許我們更好地處理可能為空的值,避免了NullPointerException的發生。 Optional類別提供了許多方法來操作潛在的空值,其中一個重要的方法是filter()。 filter()方法的作用是,如果Option

Vue中如何利用filter對資料進行格式化與處理 Vue中如何利用filter對資料進行格式化與處理 Oct 15, 2023 pm 03:50 PM

Vue中利用filter對資料進行格式化和處理在Vue中,我們可以透過使用filter來格式化資料和處理資料。 Filter是一種可以在範本中直接呼叫的函數,它可以處理要顯示的資料並傳回處理後的結果。在本文中,我們將介紹如何使用filter來格式化和處理數據,並提供具體的程式碼範例。註冊filter在Vue實例中,我們需要先註冊一個filter,以便在模

See all articles