1 : 使用Servlet处理的局限性
在通过Servlet获取中文参数 的章节中知道,可以通过
request.setCharacterEncoding("UTF-8");
正确获取UTF-8编码的中文,但是如果有很多servlet都需要获取中文,那么就必须在每个Servlet中增加这段代码。
有一个简便的办法,那就是通过Filter过滤器进行中文处理 ,那么所有的Servlet都不需要单独处理了。
2 : 使用Filter处理
创建一个 EncodingFilter ,设置如下代码
HttpServletRequest request = (HttpServletRequest) req;
request.setCharacterEncoding("UTF-8");
doFilter方法的第一个参数req,是ServletRequest 类型的,不支持setCharacterEncoding,所以要先强制转换为HttpServletRequest
package filter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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 {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
3 : 配置web.xml
配置EncodingFilter
<url-pattern>/*</url-pattern>
表示为所有的访问都使用该Filter
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>