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

一、现象:

使用pojo对象产生的json不会乱码,但使用map存放数据后,再使用json转换工具时就会产生乱码。

* 二、原因:*

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

三 、解决方法:

1、第一种方法:

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

@RequestMapping(value = "/picupload", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String uploadPicture(
            @RequestParam(value = "file", required = false) MultipartFile uploadFile,
            HttpServletRequest request) {
        Map map = null;
        if (uploadFile == null || uploadFile.isEmpty()) {
            map = new HashMap();
            map.put("error", 1);
            map.put("msg", "上传文件不能为空");
        } else {
            if (request instanceof MultipartHttpServletRequest) {
                map = picService.uploadPicture(uploadFile);
            } else {
                map = new HashMap();
                map.put("error", 1);
                map.put("msg", "当前请求类型不是multipart/form-data");
            }
        }
        String result = JsonUtils.objectToJson(map);
        return result;
    }

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

2、第二种方法(在spring MVC3.0以上这个配置是不能用的):

在配置文件中加入

<mvc:annotation-driven>
    <!-- 解决ResponseBody中文乱码 -->
    <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>

参考:http://stackoverflow.com/questions/3616359/who-sets-response-content-type-in-spring-mvc-responsebody

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值