SpringMvc中使用Interceptor與Filter的注意點


以下內容為自己的理解,如果有錯誤的地方,歡迎指正。

Filter配置在web.xml,而Interceptor配置spring-mvc.xml中,如果項目中同時使用了Filter與Interceptor,則會先執行Filter。

1、Filter中不能直接獲取spring中的service,簡單測試代碼如下:

public class TestFilter implements Filter{

    TestService testService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
        //獲取spring中的service
        testService = (TestService)applicationContext.getBean("testService");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
    }

    @Override
    public void destroy() {
        
    }

}

如果,如果要調用TestService中的方法,需要在Filter初始化時獲取。

2、Interceptor中可以直接使用注解獲取spring中的bean,簡單測試代碼如下:

 1 public class TestInterceptor implements HandlerInterceptor{
 2 
 3     @Resource
 4     ItemsServiceImpl a;
 5     @Override
 6     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
 7             throws Exception {
 8         System.out.println("執行了preHandle方法");
 9         String rt = a.say();
10         System.out.println(rt+"interceptor");
11         return true;
12     }
13 
14     @Override
15     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
16             ModelAndView modelAndView) throws Exception {
17         System.out.println("執行了postHandle方法");
18     }
19 
20     @Override
21     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
22             throws Exception {
23         System.out.println("執行了afterCompletion方法");
24     }
25     
26 }

preHandle方法在執行完Filter(如果項目配置了Filter的話)之后,執行Controller方法之前執行,如果返回false,則后面的Controller方法以及postHandle方法都不會執行。

postHandle方法在執行完Controller方法之后,返回ModelAndView之前執行,此時可以修改ModelAndView中的屬性。

afterCompletion方法在postHandle之后執行,通常執行一些資源的清理。

=====遇到有需要的在編輯=====


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM