- request.setCharacterEncoding("UTF-8");只对POST方式提交有用
- 对于GET方式 ,可以有装饰模式和适配器模式,对获取参数的函数进行重写。
- 对所有的页面进行过滤,设置编码。
-
package com.learning.filter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Enumeration; import java.util.Map; import javax.security.auth.message.callback.PrivateKeyCallback.Request; 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.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; @WebFilter(urlPatterns = "/*") public class EncodingFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // 转换对象 HttpServletRequest httpServletRequest = (HttpServletRequest) arg0; HttpServletResponse httpServletResponse = (HttpServletResponse) arg1; httpServletResponse.setContentType("text/html;charset=UTF-8"); // 对GET方式支持中文提交,可以应用装饰模式或适配器模式 ( 便于观看代码 此类写在本类之下 ) httpServletRequest = new MyWrapper(httpServletRequest); arg2.doFilter(httpServletRequest, httpServletResponse); } @Override public void init(FilterConfig filterConfig) throws ServletException { } } /* * 装饰模式实现: 1.实现被包装对象的接口 或者 继承被包装对象的自带装饰类 2.声明一个和被包装对象相同的对象 用于传参 3.运用构造函数 * 4.对需要重写的方法进行重写 */ class MyWrapper extends HttpServletRequestWrapper { private HttpServletRequest request; public MyWrapper(HttpServletRequest request) { super(request); this.request = request; } @Override public String[] getParameterValues(String name) { Map<String, String[]> map = getParameterMap(); String[] values = map.get(name); return values; } @Override public String getParameter(String name) { Map<String, String[]> map = getParameterMap(); String[] values = map.get(name); if (values==null) { return null; } return values[0]; } private boolean flag = true; @Override public Map<String, String[]> getParameterMap() { String method = request.getMethod(); if ("post".equalsIgnoreCase(method)) { try { request.setCharacterEncoding("UTF-8"); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if ("Get".equalsIgnoreCase(method)) { // get请求 Map<String, String[]> parameterMap = request.getParameterMap(); if (!flag) { // 确保get手动编码逻辑只运行一次 for (String parameterName : parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values != null) { for (int i = 0; i < values.length; i++) { try { // 处理get乱码 values[i] = new String(values[i] .getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } flag = true; } return parameterMap; } return super.getParameterMap(); } }