• 解决Spring MVC @ResponseBody返回中文字符串乱码问题


    引起乱码原因为spring mvc使 用的默认处理字符串编码为ISO-8859-1,具体参考 org.springframework.http.converter.StringHttpMessageConverter类中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");


    解决方法:

    第一种方法:

    对于需要返回字符串的方法添加注解,如下:

    @RequestMapping(value="/getUsers", produces = "application/json; charset=utf-8")
    public String getAllUser() throws JsonGenerationException, JsonMappingException, IOException
    {
    List<User> users = userService.getAll();
    ObjectMapper om = new ObjectMapper();
    System.out.println(om.writeValueAsString(users));
    DataGrid dg = new DataGrid();
    dg.setData(users);
    return om.writeValueAsString(dg);
    }

    此方法只针对单个调用方法起作用。

    第二种方法:

    在配置文件中加入

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
          <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
        </bean>
      </mvc:message-converters>
        </mvc:annotation-driven>

    第三种方法:

    返回字符串时,将字符串结果转换

    return new String("你好".getBytes(), "ISO-8859-1"); 

  • 相关阅读:
    2021.8.2—2021.8.8
    2021.7.29
    2021.7.27
    2021.7.26
    GC日志分析
    学习类加载机制笔记
    4、SpringCloud停更说明
    3、SpringCloudAlibaba版本选择
    京东、阿里的微服务架构
    nacos集群安装
  • 原文地址:https://www.cnblogs.com/coprince/p/3386163.html
Copyright © 2020-2023  润新知