웹 개발

Springboot에서 HTTP encoding charset 설정하는 방법

노루아부지 2021. 12. 10. 17:34

웹 서비스를 개발하면서 charset은 정말 중요합니다. 클라이언트와 서버가 charset이 맞지 않으면 문자가 제대로 표시되지 않는 문제가 발생할 수 있습니다.

 

아래와 같이 사용자의 정보를 리턴하는 URL이 있다고 가정해봅시다.

@RestController
public class TestController {
  @RequestMapping(name = "/test", produces = "application/json")
  public User test(HttpServletRequest req) {
    User user = new User();
    user.setUserId("admin");
    user.setUserName("홍길동");
    return user;
  }
}

 

  • @RestController가 아닌 @Controller annotation을 사용할 경우 메서드 선언부에 @ResponseBody를 추가해야 합니다.
  • produces = "application/json"대신 produces = MediaType.APPLICATION_JSON_VALUE를 사용할 수도 있습니다.

 

위 코드를 보면 produces = "application/json" 부분이 있는데 이렇게 설정하면 response header의 Content-Type에 application/json이 추가됩니다.

이 때, 응답을 받는 쪽에서 UTF-8을 원할 경우 오류가 발생하거나 문자열에 이상이 발생할 수 있습니다.

이 경우 다음과 같이 application.properties에 옵션을 추가하면 됩니다.

이 옵션들을 추가하면 response header의 값이 application/json --> application/json;charset=UTF-8로 변경되어 있는 것을 확인할 수 있습니다.

또한, request의 charset도 변경됩니다.

단, springboot의 버전에 따라 옵션이 달라집니다.

 

1. 이전 버전 설정

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

 

2. 변경된 설정

server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true

 

 

다른 application.properties의 옵션을 확인하려면 아래를 참고하시면 됩니다.

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#application-properties.server.server.servlet.encoding.enabled

 

Spring Boot Reference Documentation

This section goes into more detail about how you should use Spring Boot. It covers topics such as build systems, auto-configuration, and how to run your applications. We also cover some Spring Boot best practices. Although there is nothing particularly spe

docs.spring.io

 

728x90
loading