1.先配置web.xml
->配置过滤器
// filter-class 为写的过滤器类
实现 Filter 接口
<filter> <filter-name>EncodeFilter</filter-name> <filter-class>com.gxxy.filter.EncodeFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodeFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.写具体的过滤器类
public class EncodeFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 将服务器的响应编码格式设置为UTF-8 response.setContentType("text/html;charset=utf-8"); // 浏览器请求服务器过滤乱码 request.setCharacterEncoding("utf-8"); //只需要这一句代码即可,不需要下面注释的那样写 /*Iterator<String[]> iterator = request.getParameterMap().values().iterator(); while (iterator.hasNext()) { String[] strings = (String[]) iterator.next(); int length = strings.length; for (int i = 0; i < length; i++) { strings[i] = new String(strings[i].getBytes("iso-8859-1"), "UTF-8"); } }*/ chain.doFilter(request, response); } }