如何在Spring MVC中注册Servlet过滤器呢?
下文笔者讲述Spring MVC中注册Servlet过滤器的方法及示例分享,如下所示
Spring MVC注册Servlet过滤器的实现思路
步骤1: 编写一个Servlet过滤器 步骤2: web.xml中注册Servlet过滤器 或 JavaConfig的方式注册Servlet过滤器例
1. Servlet过滤器编写示例 package com.java265.form.web; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class ErrorHandleFilter implements Filter { @Override public void destroy() { // ... } @Override public void init(FilterConfig filterConfig) throws ServletException { // } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(request, response); } catch (Exception ex) { request.setAttribute("errorMessage", ex); request.getRequestDispatcher("/WEB-INF/views/jsp/error.jsp") .forward(request, response); } } } //Spring XML //在Spring MVC + XML配置中,可使用web.xml注册过滤器 web.xml <filter> <filter-name>errorHandlerFilter</filter-name> <filter-class>com.java265.form.web.ErrorHandleFilter</filter-class> </filter> <filter-mapping> <filter-name>errorHandlerFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> //Spring JavaConfig //在Spring MVC + JavaConfig //不使用web.xml文件 //可使用初始化程序类注册过滤器 package com.java265.form.config.servlet3; import javax.servlet.Filter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import com.java265.form.config.SpringRootConfig; import com.java265.form.config.SpringWebConfig; import com.java265.form.web.ErrorHandleFilter; public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //... @Override protected Filter[] getServletFilters() { return new Filter[]{new ErrorHandleFilter()}; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。