package test.encoding;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 SetCharacterEncoding implements Filter {
protected String encoding=null;
protected FilterConfig filterconfig=null;
protected boolean ignore=true;
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain arg2) throws IOException, ServletException {
if(ignore||(request.getCharacterEncoding()==null)){
String encoding=this.selectEncoding(request);
if(encoding!=null){
request.setCharacterEncoding(encoding);
}
}
arg2.doFilter(request, response);
}
public void init(FilterConfig filterconfig) throws ServletException {
this.filterconfig=filterconfig;
String encoding=filterconfig.getInitParameter("encoding");
String value=filterconfig.getInitParameter("ignore");
if(value==null)
{
ignore=true;
}
else if(value.equalsIgnoreCase("true")){
ignore=true;
}
else if(value.equalsIgnoreCase("yes")){
ignore=true;
}
else{
ignore=false;
}
}
public String selectEncoding(ServletRequest request){
return (this.encoding);
}
}
<filter> <filter-name>setCharacterEncoding</filter-name>
<filter-class>test.encoding.SetCharacterEncoding</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>setCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>