Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

끄적끄적

[spring] filter에서 예외응답하기 본문

개발

[spring] filter에서 예외응답하기

으아아아앜 2020. 3. 9. 17:37

- ResponseHandler 생성

@Component
public class ResponseHandler {
    public void response400(HttpServletResponse res, Object object) throws IOException {
        res.setStatus(400);
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json; charset=UTF-8");
        String json = objectMapper.writeValueAsString(object);
        PrintWriter out = res.getWriter();
        out.print(json);
    }
    public void signInResponse400(HttpServletResponse res, String message) throws IOException {
        response400(res,new ApiError(HttpStatus.BAD_REQUEST, Arrays.asList(new GlobalErrorContent(message))));
    }
    public void jwtResponse400(HttpServletResponse res, String message) throws IOException {
        response400(res,new ApiError(HttpStatus.BAD_REQUEST, Arrays.asList(new GlobalErrorContent(message))));
    }
    public static Locale getLocale(HttpServletRequest req){
        Optional<String> langOp = Optional.ofNullable(req.getParameter("lang"));
        String lang = langOp.orElse("ko");
        return new Locale(lang);
    }
}

 

※ 필터에서 locale을 사용하기 위해서 다국어를 위해 설정했던 lang 파라미터를 확인합니다.

public static Locale getLocale(HttpServletRequest req){
  Optional<String> langOp = Optional.ofNullable(req.getParameter("lang"));
  String lang = langOp.orElse("ko");
  return new Locale(lang);
}
  • 사용자의 req를 확인하여, lang 파라미터의 값을 얻습니다.
  • 디폴트 locale 설정은 Optional.orElse 메소드를 활용하고, 새 locale을 생성하여 return합니다.
  • LocaleContextHolder.getLocale()로는 필터에서 의도한 로케일을 얻을 수 없었습니다.

 

 

사용 예시

@Component
@RequiredArgsConstructor
public class JwtFilterFailureHandler implements AuthenticationFailureHandler {
    private final MessageSource validMessageSource;
    private final ResponseHandler responseHandler;
    @Override
    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException e) throws IOException, ServletException {
        String message = validMessageSource.getMessage(e.getMessage(), null, ResponseHandler.getLocale(req));
        responseHandler.jwtResponse400(res,message);
    }
}

 

Comments