程序設(shè)計(jì):添加一個(gè)專門測(cè)試亂碼的前端和后端。
  
這樣可以分析測(cè)試各種亂碼情況:form表單提交,ajax提交。以此來(lái)推測(cè)出哪里出問(wèn)題,程序大致是如何設(shè)置的。 ajax的post提交,后臺(tái)不用處理,中文也不會(huì)亂碼。(因?yàn)閖query處理了) ajax的get提交,后臺(tái)需要處理,要么getBytes(),new String();要么改tomcat配置。
filter中使用動(dòng)態(tài)代理對(duì)全局進(jìn)行編碼: public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; //使用動(dòng)態(tài)代理完成全局編碼 HttpServletRequest enhanceRequset = (HttpServletRequest) Proxy.newProxyInstance( req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //對(duì)getParameter方法進(jìn)行增強(qiáng) String name = method.getName();//獲得目標(biāo)對(duì)象的方法名稱 if("getParameter".equals(name)){ String invoke = (String) method.invoke(req, args);//亂碼 //轉(zhuǎn)碼 invoke = new String(invoke.getBytes("iso8859-1"),"UTF-8"); return invoke; } return method.invoke(req, args); } } ); chain.doFilter(enhanceRequset, response); }
|