•
通过配置参数
encoding
指明使用何种字符编码
,
以处理
Html Form
请求参数的中文问题
1.新建一个Filter接口的实现类
//解决全站的post乱码
public class CharacterEncodingFilter implements Filter {
private FilterConfig filterConfig;
private String defaultCharset = "UTF-8";
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String charset = this.filterConfig.getInitParameter("charset");
if(charset == null){
charset = defaultCharset;
}
request.setCharacterEncoding(charset); //这句代码智能解决post方式的乱码问题,不能解决get方式的乱码问题
chain.doFilter(request, response);
}
public void destroy() {
// TODO Auto-generated method stub
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
}
2.配置web.xml文件
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>cn.itcast.web.filter.example.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>