springboot返回前端中文乱码的解决方法

时间:2021-07-20 13:06:32

尝试了各种防止中文乱码的方式,但是还是乱码;最后还是细节问题导致;

解决方式:

以及俩种方式是百度的,我的问题不是这俩块

1.在requestMapping 中添加 produces

?
1
2
3
4
5
@RequestMapping(
 value = "/login",
 produces = "application/json;charset=utf-8",
 method = RequestMethod.POST
)

2.在application.yml 中添加配置

?
1
2
3
4
5
6
spring:
  http:
    encoding:
      force: true
      charset: utf-8
      enabled: true

3.解决单个字符串乱码

?
1
String name = new String(user.getName().getBytes("ISO-8859-1"),"UTF-8");

我的乱码问题的解决方式

接口添加 @ResponseBody 是返回对象到前端就会展示成json格式,但有的时候会乱码;
比如下面的写法

?
1
2
3
User user = new User();//假装有数据
JSONObject output = new JSONObject();
output.put("userInfo": user);

user添加到JSONObject中 user里面的中文就会乱码;

返回前端的数据还是先将对象转成 JSON然后在 return

?
1
2
3
User user = new User();//假装有数据
JSONObject output = new JSONObject();
output.put("userInfo": JSON.toJSON(user));

到此这篇关于springboot返回前端中文乱码的解决方法的文章就介绍到这了,更多相关springboot返回前端中文乱码内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_34158598/article/details/86092713