后台接收出现html实体编码或乱码的处理

表单提交时会将字符等以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);

 

posted @   zhouxg72  阅读(191)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示