2012-02-09 20 views

回答

11

創建過濾器只是使實現了javax.servlet.Filter接口,你的情況可能是這樣的

public class CookieFilter implements Filter { 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
        HttpServletRequest request = (HttpServletRequest) req; 
   
     Cookie[] cookies = request.getCookies(); 
     if (cookies != null){ 
      for (Cookie ck : cookies) { 
      if ("nameOfMyCookie".equals(ck.getName())) { 
       // read the cookie etc, etc 
       // .... 
       // set an object in the current request 
       request.setAttribute("myCoolObject", myObject) 
      } 
     } 
        chain.doFilter(request, res); 
    } 
    public void init(FilterConfig config) throws ServletException { 
     // some initialization code called when the filter is loaded 
    } 
    public void destroy() { 
     // executed when the filter is unloaded 
    } 
} 

一類則聲明過濾器在web.xml

<filter> 
    <filter-name>CookieFilter</filter-name> 
    <filter-class> 
        my.package.CookieFilter 
    </filter-class> 
</filter> 
<filter-mapping> 
    <filter-name>CookieFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

在你的控制這一點上只是檢查是否使用request.getAttribute(「myCoolObject」)

+0

春天注入的依賴關係到我的過濾器的要求存在attibute? – Blankman 2012-02-09 03:11:07

+2

如果過濾器是通過彈簧應用程序上下文實例化的,Spring只能注入依賴關係。您的過濾器由servlet容器實例化。不過,您可以在過濾器中訪問應用程序上下文。看看這裏:http://forum.springsource.org/showthread.php?31655-How-to-access-application-context-from-a-filter – MarcFasel 2012-02-09 05:29:38

+0

春季啓動的任何例子? – unknown 2017-11-13 08:49:19

相關問題