後臺接收出現html實體編碼或亂碼的處理
阿新 • • 發佈:2022-03-25
表單提交時會將字元等以html實體編碼提交,對實體中的String型別的欄位進行格式化處理
public static String unescapeHtml(String str) { if (StringUtils.isNotBlank(str)) { str = formatBlank(StringEscapeUtils.unescapeHtml(str)); } return str; } private static String formatBlank(String str) {byte[] space = new byte[]{(byte) 0xC2, (byte) 0xA0}; String UTFSpace = new String(space, StandardCharsets.UTF_8); return str.replace(UTFSpace, StringUtils.SPACE); }
public static <T> T formatEntity(T t) throws Exception { Class<?> clz = t.getClass(); String stringType= "java.lang.String"; BeanInfo beanInfo = Introspector.getBeanInfo(clz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String name = propertyDescriptor.getPropertyType().getName();if (StringUtils.equals(name, stringType)) { Method readMethod = propertyDescriptor.getReadMethod(); Object value = readMethod.invoke(t); if(value != null) { String val = String.valueOf(value); if (StringUtils.isNotBlank(val)) { val = unescapeHtml(val); Method writeMethod = propertyDescriptor.getWriteMethod(); writeMethod.invoke(t, val); } } } } return t; }
get請求帶中文時,後臺接收亂碼
byte[] bytes = str.getBytes(StandardCharsets.ISO_8859_1); str = new String(bytes, StandardCharsets.UTF_8);