1.java类:
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;
public class EncodingFilter
implements Filter
{
private String charset = "UTF-8";
public void destroy()
{
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
if (req.getMethod().equalsIgnoreCase("GET")) {
if (!(req instanceof GetRequest))
req = new GetRequest(req, this.charset);
}
else {
req.setCharacterEncoding(this.charset);
}
chain.doFilter(req, response);
}
public void init(FilterConfig fConfig) throws ServletException
{
String charset = fConfig.getInitParameter("charset");
if ((charset != null) && (!(charset.isEmpty())))
this.charset = charset;
}
}
2.在web.xml中添加
<!-- 处理全站请求编码,无论是GET还是POST,默认是UTF-8 -->
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>cn.servlet.filter.EncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>