过滤器使用之全站乱码处理
Posted 狂妄的老头
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了过滤器使用之全站乱码处理相关的知识,希望对你有一定的参考价值。
1 public class EncodeFilter implements Filter { 2 private String encode; 3 public void init(FilterConfig config) throws ServletException { 4 encode = config.getInitParameter("encode"); 5 } 6 class MyHSR extends HttpServletRequestWrapper{ 7 private HttpServletRequest request; 8 private boolean hasEncode = false; 9 public MyHSR(HttpServletRequest request) { 10 super(request); 11 this.request = request; 12 } 13 @Override 14 public Map<String,String[]> getParameterMap() { 15 //获取提交的方式post/get 16 if("POST".equals(request.getMethod())){ 17 try { 18 request.setCharacterEncoding(encode); 19 } catch (UnsupportedEncodingException e) { 20 e.printStackTrace(); 21 } 22 return request.getParameterMap(); 23 }else if("GET".equals(request.getMethod())){ 24 //定义一个Map集合对象 25 Map<String,String[]> map = request.getParameterMap(); 26 if(!hasEncode){ 27 //遍历map 28 for(Map.Entry<String, String[]> entry:map.entrySet()){ 29 //获取原来的vals 30 String[] vals = entry.getValue(); 31 //遍历数组处理乱码 32 for (int i = 0;i<vals.length;i++) { 33 try { 34 vals[i] = new String(vals[i].getBytes("ISO8859-1"),encode); 35 } catch (UnsupportedEncodingException e) { 36 e.printStackTrace(); 37 } 38 } 39 } 40 hasEncode = true; 41 } 42 return map; 43 }else{//既不是get方式也不是post方式 44 return super.getParameterMap(); 45 } 46 } 47 @Override 48 public String[] getParameterValues(String name) { 49 return getParameterMap().get(name); 50 } 51 @Override 52 public String getParameter(String name) { 53 return getParameterValues(name)==null?"":getParameterValues(name)[0]; 54 } 55 } 56 public void doFilter(ServletRequest request, ServletResponse response, 57 FilterChain chain) throws IOException, ServletException { 58 response.setContentType("text/html;charset=utf-8"); 59 chain.doFilter(new MyHSR((HttpServletRequest)request), response); 60 61 } 62 public void destroy() { 63 } 64 }
web.xml配置别忘了写啊!
以上是关于过滤器使用之全站乱码处理的主要内容,如果未能解决你的问题,请参考以下文章