169. Spring Boot integrates jersey Chinese garbled perfect solution

 

【Video & Communication Platform】

à SpringBoot Video 

http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

à  SpringCloud Video

http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

à Spring Boot source code 

https://gitee.com/happyangellxq520/spring-boot

à Spring Boot communication platform 

http://412887952-qq-com.iteye.com/blog/2321532

 

Origin of need:

       When recording the video " Spring Boot integration jersey ", when returning to Chinese, garbled characters appeared. At the time of integration, it was returned in English, so this problem was not found. Here is a solution to this problem.

Request source code:

       We first provide the source code of the request method here:

@GET//get request.
    @Path("/getUser")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String,Object> getUser(){
       Map<String,Object> map = new HashMap<String,Object>();
       map.put("id","1000");
       map.put("name","张三");
       map.put("age","25");
       System.out.println(map.get("name"));
       return map;
    }

 

 

Option One

       Through the above code, we can know that the name in the map object will not be garbled, then when returning, response There is no encoding set, so how to specify the encoding when returning, just need a little Modify the above code to:

@GET//get request.
@Path("/getUser")
@Produces(MediaType.APPLICATION_JSON+";charset=UTF-8")

 

       Here we manually configure utf-8 encoding.

 

Option II

       Let's talk about the problems with the first solution:

( 1 ) Coding is inconvenient, and every developer needs to do coding;

( 2 ) There are many places to be adjusted if the encoding is adjusted or Chinese is discovered later;

3)代码侵入性太强;

       那么我们有更好的方案嘛,当然有,只需要在application.properties配置两个信息:

spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8

 

       到这里就可以完美解决中文乱码问题。

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326517984&siteId=291194637