package org.zln.utils.filter; import javax.servlet.*; import java.io.IOException; /** * Created by sherry on 2015/2/6 0006 15:40. */ public class CharactorFilter implements Filter { String encoding = null; @Override public void init(FilterConfig filterConfig) throws ServletException { encoding = filterConfig.getInitParameter("encoding"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (encoding != null){ servletRequest.setCharacterEncoding(encoding); servletResponse.setContentType("text/html;charset="+encoding); System.out.println(" ---字符过滤---"+encoding); } filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { encoding = null; } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!--字符过滤器--> <filter> <filter-name>CharactorFilter</filter-name> <filter-class>org.zln.utils.filter.CharactorFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharactorFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>