BugNote
HttpServletResponse getWriter()를 사용하여 직접 body를 넣어줄때 한글 출력 안됨 현상
제뉴어리맨
2022. 10. 31. 14:45
private String contentType = "application/json";
상황
서버에서 클라이언트의 잘못된 요청으로 인해 exception을 터뜨리고,
해당 exception 정보를 클라이언트에게 전달하기 위해,
직접 Response에 데이터를 넣어야 하는 상황이였다.
아래는 해당 코드이다
private void sendErrorResponse(HttpServletResponse response, ExceptionCode exceptionCode) throws IOException {
ErrorResponse errorResponse = ErrorResponse.of(exceptionCode);
String content = gson.toJson(errorResponse);
response.setContentType(contentType);
response.setStatus(exceptionCode.getStatus());
response.getWriter().write(content);
}
그리고, 데이터에 한글을 넣었을때 포스트맨으로 확인한 결과화면은 아래이다.
에러 메세지
원인
보낸 데이터를 어떻게 인코딩할지 브라우저에게 알려주어야하는데,
단순히 json 데이터라는 정보만 보냈다.
즉,
수정 전
private String contentType = "application/json";
해결 방법
수정 후
private String contentType = "application/json;charset=UTF-8";
결론
영문, 숫자와 같은 기본적은 데이터 이외의 데이터를 보낼때는 명확하게 디코딩할 타입을 명시하여 주자.