src/com/Encoding.java
package com; 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 Encoding implements Filter{ protected String encoding=null; protected FilterConfig config; @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub if(request.getCharacterEncoding()==null){ String encode=getEncoding(); if(encode!=null){ request.setCharacterEncoding(encode); response.setCharacterEncoding(encode); } } chain.doFilter(request, response); } @Override public void init(FilterConfig config) throws ServletException { // TODO Auto-generated method stub this.config=config; this.encoding=config.getInitParameter("Encode"); } protected String getEncoding(){ return encoding; } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <filter> <filter-name>EncodeFilter</filter-name> <filter-class>com.Encoding</filter-class> <init-param> <param-name>Encode</param-name> <param-value>GB2312</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodeFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>