230314 TIL #32 getWriter() 한글 깨짐

김춘복·2023년 3월 14일
0

TIL : Today I Learned

목록 보기
32/494

230314 Today I Learned

Spring 3주차. 과제 Lv.4와 5를 동시에 구현했다. 핵심기능 구현은 비교적 쉬웠지만 예외처리에서 애를 먹었다. 오늘 헤맸던 부분을 아래에 정리해두었다.


getWriter() 한글 깨짐

  • 문제 : Controller의 예외는 Global Exception Handler에서 잡히고 한글로 된 에러메세지도 문제 없이 잘 나왔다. 하지만 JwtAuthFilter의 토큰 에러는 Global Exception Handler에서 잡히지 않아 필터 내에 따로 ExceptionHandler를 만들었다.
// 위에서 검증시
jwtExceptionHandler(response, "토큰이 유효하지 않습니다.", HttpStatus.BAD_REQUEST);
return;
--------------------------------------------------------------

    public void jwtExceptionHandler(HttpServletResponse response, String msg, HttpStatus httpStatus) {
        response.setStatus(httpStatus.value());
        response.setContentType("application/json");
        try {
            String json = new ObjectMapper().writeValueAsString(new MessageResponseDto(msg,httpStatus));
            response.getWriter().write(json);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

하지만 이렇게 예외처리를 하면 한글로 된 에러세지가 "??? ???? ????."처럼 깨져서 떴다.

  • 시도 : Global Exception Handler로 가게 throw로 예외처리를 시도해봤으나 실패.
    그리고 @ExceptionHandler를 달아 필터 내부에 만들어 봤으나 이것도 실패.
    결국 구글링으로 response.getWriter() 한글 깨짐으로 검색해보니 해답이 나왔다.

  • 해결 : response.getWriter() 처럼 PrintWriter기능을 사용할 시 가끔 한글 깨짐이 발생하는데 이럴때는 문자 인코딩 방식을 UTF-8로 미리 세팅해주면 한글이 깨지지 않는다.

response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");

이 두줄을 위의 jwtExceptionHandler 윗줄에 넣으니 한글이 깨지지 않고 정상출력 되었다.

  • 알게된점 :
    Global Exception Handler @ControllerAdvice는 필터쪽의 에러를 처리하지 못한다. PrintWriter 기능 사용시 UTF-8로 인코딩하면 한글이 깨지지 않는다.

profile
꾸준히 성장하기 위해 매일 log를 남깁니다!

0개의 댓글