멍두의 개발새발
[스프링] [에러해결] 모든 http response의 한글 깨짐을 한방에 해결하기 본문
반응형
💥 문제
문제 1 : ios 앱 개발을 하면서 프론트 측에서 Http response Body의 한글 값이 깨졌다.
해결 1 : 그래서 항상 헤더에 utf-8 인코딩을 넣어서 보내줬다.
public ResponseEntity<CardInfoResponseDto> postCardInfo(@PathVariable("cardId") Long cardId) {
CardInfoResponseDto cardInfoResponseDto = cardInfoService.getCardInfo(1L, cardId);
//utf-8인코딩
HttpHeaders headers = new HttpHeaders();
MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
headers.setContentType(mediaType);
return ResponseEntity.ok().headers(headers).body(cardInfoResponseDto);
}
문제 2 : 당연히 에러 메세지에서도 한글이 깨졌는데 에러는 @RestControllerAdvice로 처리하고 있어 내가 헤더를 넣어줄 수가 없었다.
{ exceptionName: AiConnectionException,
message: ìì± ìì±ì ì¤í¨íììµëë¤ }
한글이 깨진 흉측한 모습..
⭐ 해결
아주 간단한 방법으로 해결했다.
applicaiton.properties에 아래 코드를 넣어주면 된다.
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true
- server.servlet.encoding.charset
- http resposne와 request의 "Content-Type" header 가 명시적으로 선언되어있지 않으면 자동으로 추가
- default value가 UTF-8이기때문에 빼주어도 된다. 만약 UTF-8이 아니라 다른 걸로 encoding해주고 싶으면 꼭 설정해주어야함
- server.servlet.encoding.force
- 위에 명시한 인코딩을 헤더에 강제로 넣어주는 것
- 이게 없으면 Content-Type에 chatset값이 안 나옴
이제 response header에 chatset=utf-8이 잘 찍히는 것을 볼 수 있다.
가끔 참 쉬운 방법으로 문제가 해결되는 것 같다
반응형
'Programming > Spring' 카테고리의 다른 글
[JPA] Entity에서 사용되는 Annotation 정리 (@Table, @Entity, @Column, @Enumerated, @Temporal .. ) (2) | 2025.05.26 |
---|---|
[스프링] DTO에 @NoArgsConstructor와 @Gettter이 필요한 이유 (0) | 2024.07.30 |
[스프링] - findByIN절, jdbc batchUpdate (bulk Insert)로 쿼리 개선 (0) | 2024.05.29 |
[스프링] @RestControllerAdvice 리팩토링 (1) | 2024.04.14 |
[스프링] WAS WebApplicationServer란? (1) | 2024.04.10 |