CharacterEncodingFilter.java

package org.com.util;

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 CharacterEncodingFilter implements Filter {

private String characterEncoding = null;
private boolean enabled;

@Override
public void destroy() {
// TODO Auto-generated method stub
characterEncoding = null;
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
if (enabled || characterEncoding != null) {
request.setCharacterEncoding(characterEncoding);
response.setCharacterEncoding(characterEncoding);
}
chain.doFilter(request, response);
}

@Override
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
characterEncoding = config.getInitParameter("characterEncoding");
enabled = "true".equalsIgnoreCase(config.getInitParameter("enabled").trim());
}

}

web.xml
<!-- 字符转码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>
org.com.util.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>characterEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>enabled</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>