preface
Spring Boot is a new framework from the Pivotal team designed to simplify the initial setup and development process for new Spring applications. The framework uses a specific way to configure so that developers no longer need to define boilerplate configurations. Spring Boot is considered the “successor” to Spring MVC. It can automatically configure for us, and if the default configuration does not meet our requirements, we can replace the auto-configuration class and use our own configuration.
How to solve the problem of Chinese garbled characters in Spring Boot?
1. Write apis that return content in Chinese;
Add an API to controller in any Spring Boot project like this:
@GetMapping("/api/hello") public JSONObject sayHello() { JSONObject test = new JSONObject(); test.put("name", "dylanz"); Test. Put ("say", "hello "); return test; }Copy the code
2. Chinese garble demonstration;
We will find that the API return, The English display is normal, but the Chinese is garbled! The reason does not analyze first, let’s see how to solve first!
3. Solve Chinese garbled characters :(method 1);
How to solve this problem is very simple, modify the API:
@GetMapping("/api/hello") public JSONObject sayHello() { HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse(); assert response ! = null; response.setCharacterEncoding("UTF-8"); JSONObject test = new JSONObject(); test.put("name", "dylanz"); Test. Put ("say", "hello "); return test; }Copy the code
Utf-8 character set utF-8 character set utF-8
Repair Chinese garbled characters
The character set is UTF-8
4. Solve Chinese garbled characters :(method 2);
This is simpler than the first method, just specify produces on the API, as in:
@GetMapping(value = "/api/hello", produces = "application/json; charset=UTF-8") public JSONObject sayHello() { JSONObject test = new JSONObject(); test.put("name", "dylanz"); Test. Put ("say", "hello "); return test; }Copy the code
This way can also solve the Chinese garble problem, effective test!
5. Solve Chinese garbled characters :(method 3) – solve Chinese garbled characters globally;
The above two ways to solve Chinese garbled is simple, but need to add an API, this does not conform to our temperament ah, the correct posture should be: global solution to the problem of Chinese garbled!
Create a new charsetConfig. Java class in the config package (no name is required, CharsetConfig is not required) and write code in this configuration class:
package com.github.dylanz666.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* @author : dylanz
* @since : 11/15/2020
*/
@Configuration
public class CharsetConfig extends WebMvcConfigurationSupport {
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
return new StringHttpMessageConverter(
StandardCharsets.UTF_8);
}
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(responseBodyConverter());
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat
);
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
Copy the code
Because I use fastjson, added in configureMessageConverters fastjson configuration code for Chinese support.
After writing, delete (method 1) and (method 2) support code, restart the project, Chinese support has become global effect, effective test!
2. Chinese normal display demonstration;
1. Analysis of Chinese garbled characters;
1). Print the original character set using the code used in step 3 to solve the garble problem:
@GetMapping("/api/hello") public JSONObject sayHello() { HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse(); assert response ! = null; System.out.println("Default charset: " + response.getCharacterEncoding()); JSONObject test = new JSONObject(); test.put("name", "dylanz"); Test. Put ("say", "hello "); return test; }Copy the code
2). After starting the project again and accessing the API:
Chinese garbled characters cause:
The default character set for Spring Boot is ISO-8859-1 (utF-8 if a String is returned).
2. The default character set can also be seen in a browser or postman:
Default character set
3). We solve the garbled character set:
conclusion
So far, we have solved the problem of Chinese garbled characters in Spring Boot project from two dimensions and three methods:
-
API set character set separately;
-
Global setting character set;
Xiaobian share content is over here! Like xiaobian to share technical articles can like attention oh!
Here are some spring Boot technical information and interview questions
Public account: Kylin bug