在java中增加了过滤器filter,一般我们定义的filter都要继承filter接口从而实现dofilter方法,filter的配置,我们可以在web.xml中进行配置,配置如下:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> <filter> <filter-name>proxyFilter</filter-name> <filter-class>com.filter.ProxyFilter</filter-class> <init-param> <param-name>configFile</param-name> <param-value>/config.json</param-value> </init-param> </filter> <filter-mapping> <filter-name>proxyFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
当我们想在程序中使用filter的param时,可以通过filterConfig.getInitParameter("configFile")的形式来获得配置数据,在dofilter中,我们希望改变httpServletRequest的封装的属性就需要用到装饰类 HttpServletRequestWrapper,想改变request的那个方法就要用继承该wrapper类然后重写servletRequest的那个方法。使用httpServletResponse对象来初始化我们想要的对象。例如想修改request的getPathInfo,实现如下:
public class HttpProxyRouterRequest extends HttpServletRequestWrapper { public String _pathInfo = null; public HttpProxyRouterRequest(HttpServletRequest request) { super(request); // TODO Auto-generated constructor stub } @Override public String getPathInfo() { if ( this._pathInfo == null ){ _pathInfo = super.getPathInfo(); if(_pathInfo == null){ _pathInfo = HttpUtils.getPathInfo(getRequestURI(), getContextPath()); } } return this._pathInfo; }
原文地址:http://blog.csdn.net/chunlei_zhang/article/details/39137695