Servlet过滤器

1、定义过滤器类
public class CharacterFilter implements Filter { private FilterConfig filterConfig=null; private String encoding=null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig=filterConfig; this.encoding=filterConfig.getInitParameter("encoding"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //设置编码格式 if(request.getCharacterEncoding()==null){ String encoding=this.getEncoding(); if(encoding!=null){ request.setCharacterEncoding(encoding); } //传递过滤器 chain.doFilter(request, response); } } public void destroy() { filterConfig=null; encoding=null; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } }

 2、配置web.xml文件

<!-- 字符串过滤器 --> <filter> <filter-name>characterFilter</filter-name> <filter-class> com.snowlucky.servlet.filter.CharacterFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

你可能感兴趣的:(servlet,String,filter,null,Class,encoding)