开发中编码问题
编码问题 重要的事情说三遍。
项目中前台传入汉字模糊查询 翻页后 汉字总会乱码。
自以为机智的我 在每次传入查询条件的时候都判断当前编码格式 然后全部转换为自己想要的编码。那么继续自以为机智的我 机智的发现我
每一次点击下一页被编码过的数据重新进行编码。相当于编码上再进行编码。想到了通过循环判断解码次数(因为涉及到页数并不算多 模糊查询条件只有一个 权且不考虑性能的问题)。
然后 每次模糊查询后 响应的点击下一页下一页 倒也是没有问题,可以正常的查询 。下面给出让人醉了的代码:
1 /* String method = getRequest().getMethod(); 2 if( method.equals("GET") ){//&& page==2 3 String scode = CharsetTran.getEncoding(channelname); 4 System.out.println(scode); 5 String cn = ""; 6 if (!scode.equals("UTF-8")) { 7 cn= new String(channelname.getBytes(scode),"utf-8"); 8 } 9 if (page>2) { 10 for (int i = 2; i < page; i++) { 11 cn = new String(cn.getBytes("ISO-8859-1"),"utf-8"); 12 } 13 } 14 channelname = cn; 15 channelStatistics.setChannelname(channelname); 16 }*/ 17 18 // if( method.equals("GET") && page>2 ){//&& page==2 19 // String cn = new String(channelname.getBytes("gb2312"),"Utf-8"); 20 // System.out.println(cn); 21 // channelname = cn; 22 // channelStatistics.setChannelname(channelname); 23 // }
1 class CharsetTran { 2 /** 3 * @desc判断字符串的编码 4 * @param str 5 * @return 6 */ 7 public static String getEncoding(String str) { 8 String encode = "GB2312"; 9 10 try { 11 if (str.equals(new String(str.getBytes(encode), encode))) { 12 String s = encode; 13 return s; 14 } 15 } catch (Exception exception) { 16 } 17 18 encode = "UTF-8"; 19 try { 20 if (str.equals(new String(str.getBytes(encode), encode))) { 21 String s2 = encode; 22 return s2; 23 } 24 } catch (Exception exception2) { 25 } 26 27 encode = "GBK"; 28 try { 29 if (str.equals(new String(str.getBytes(encode), encode))) { 30 String s3 = encode; 31 return s3; 32 } 33 } catch (Exception exception3) { 34 } 35 36 encode = "ISO-8859-1"; 37 try { 38 if (str.equals(new String(str.getBytes(encode), encode))) { 39 String s1 = encode; 40 return s1; 41 } 42 } catch (Exception exception1) { 43 } 44 45 return ""; 46 } 47 48 }
最后发现 当随机点击页码的时候 我无法判断该解码几次,当然或许我可以在页面添加一个js监控事件 用于监控模糊查询文本框里的内容,以及在内容无改变下 点击页码次数 传入后台进行判断解码次数。不过如果真是样子的话,我也是醉了。
因为之前我已经统一过了框架编码(前后台编码、velocity编码等),而且每一次页码点击都会引起编码的再编码。联想到每一次请求都是经过中间件发布 那么只有把中间件的编码进行统一。进行设置好,发现不再用进行判断解码,可以正常进行查询。。。。。。
以下列出tomcat 修改编码的方式:
conf 文件夹下 server.xml文件 修改:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
朱雀桥边野草花,乌衣巷口夕阳斜。
旧时王谢堂前燕,飞入寻常百姓家。
浙公网安备 33010602011771号