springboot的分布式开发中,偶尔会遇到中文参数传递乱码的问题,并且当前遇到的是只有某一台电脑上才出现该情况,为此在接受参数的工程接口处添加了一个判断是否中文,如果否则做转换(前提是这个参数必须只能是中文)
1 @RequestMapping(value = "/getCarList", method = RequestMethod.GET) 2 public ResultObject getCarByCpName(@RequestParam(value = "cpName",required = true)String cpName,@RequestParam(value = "carNo",required = false)String car_no) { 3 4 char[] isc = cpName.toCharArray(); 5 boolean is = true; 6 for (char c : isc) { 7 is = isChinese(c); 8 if (!is) break; 9 } 10 //boolean isc = isChinese(cpName.getBytes()); 11 if (!is) { 12 try { 13 cpName = new String(cpName.getBytes("ISO-8859-1"),"UTF-8"); 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } 17 } 18 ResultObject rst = commonService.getCarByCpName(cpName, car_no); 19 return rst; 20 } 21 22 /** 23 * 判断字符是否是中文 24 * 25 * @param c 字符 26 * @return 是否是中文 27 */ 28 public static boolean isChinese(char c) { 29 Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); 30 if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS 31 || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS 32 || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A 33 || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION 34 || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION 35 || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { 36 return true; 37 } 38 return false; 39 }
如上所示,因为参数设置了必须有,所以没做空判断,首先将字符串转换为char数组,然后循环检测所有字符,如果不是中文则将原字符串做转换