UTF-8过滤器
package sktbbs.common.base;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;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class EncodingFilter implements Filter {protected FilterConfig filterConfig;private String targetEncoding = "UTF-8";/** * 初始化过滤器 */public void init(FilterConfig config) throws ServletException {this.filterConfig = config;this.targetEncoding = config.getInitParameter( "encoding" );}/** * 进行过滤处理,这个方法最重要,所有过滤处理的代码都在此实现 */public void doFilter(ServletRequest srequest, ServletResponse sresponse,FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest)srequest;HttpServletResponse response = (HttpServletResponse)sresponse;request.setCharacterEncoding( targetEncoding );response.setContentType("text/html;charset="+targetEncoding);//把处理权发送到下一个chain.doFilter( srequest , sresponse );}/** * 销毁过滤器 */public void destroy() {this.filterConfig = null;}}
?
?
web.xml
?
<filter> <filter-name>encoding</filter-name> <filter-class>com.cc.common.base.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
?