jun - 云代码空间
—— 相信 ,梦
package cn.itcast.web.filter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; 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.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; //全局编码过滤 public class EncodingFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // 1.将请求与响应对象强制转换成http协议下的 HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; // 2.完成操作--处理编码 // 将request对象进行增强,增强后的request对象可以解决编码问题----使用装饰来增强. // 3.放行 chain.doFilter(new MyRequest(request), response); } public void init(FilterConfig arg0) throws ServletException { } } // 自定义的的增强类 class MyRequest extends HttpServletRequestWrapper { private HttpServletRequest request; private boolean flag = true;// 开关 public MyRequest(HttpServletRequest request) { super(request); this.request = request; } // 得写方法,来解决编码问题 @Override public String getParameter(String name) { if (name == null) { return null; } String[] st = getParameterMap().get(name); if (st == null || st.length == 0) { return null; } return st[0]; } @Override public String[] getParameterValues(String name) { if (name == null) { return null; } String[] st = getParameterMap().get(name); return st; } @Override public Map<String, String[]> getParameterMap() { // 1.得到请求方式 String method = request.getMethod(); if ("post".equalsIgnoreCase(method)) { // 解决post编码 try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return request.getParameterMap(); } else { // get请求 // 2.得到所有请求参数 Map<String, String[]> map = request.getParameterMap(); if (flag) { // 对map集合中的信息只进行一次转码 // 3.对Map集合中的value的每一个元素进行转码操作 for (String key : map.keySet()) { // 得到map的所有的key String[] value = map.get(key); // 根据key获取value // 4.对value中所有元素进行编码处理 for (int i = 0; i < value.length; i++) { try { value[i] = new String( value[i].getBytes("iso8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } flag = false; } return map; } } }
<!-- 全局编码过滤器 --> <filter> <filter-name>encoding</filter-name> <filter-class>cn.itcast.web.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>