后台接收出现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  阅读(190)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示