Spring boot/기본 정리

AOP에서 HttpServletRequest 사용하기

코딩딩코 2022. 11. 1. 21:06

AOP는 메서드에 관하여 메서드 호출 전, 후에 어떠한 로직을 하고 싶을 때 사용을 합니다.

 

@Before(value = "enableValidCheck()")
public void validCheck(JoinPoint joinPoint) {
    Object[] args = joinPoint.getArgs();

    for(Object arg : args) {
        if(arg.getClass() == BeanPropertyBindingResult.class) {
            BindingResult bindingResult = (BindingResult) arg;

            Map<String, String> errorMap = new HashMap<String, String>();
            if(bindingResult.hasErrors()) {

                bindingResult.getFieldErrors()
                    .forEach(error -> errorMap.put(error.getField(), error.getDefaultMessage()));

                log.error(">>>>> 유효성 검사 실패: {}", errorMap);
                throw new CustomValidationApiException("유효성 검사 실패", errorMap);
            }

        }
    }

}

위의 코드는 회원가입 시 유효성 검사를 위해 AOP로 따로 분리시켜 놓은 로직입니다.

여기서 joinPoint를 이용하면 해당 메서드의 데이터를 가지고 올 수 있습니다.

joinPoint.getArgs()를 통해서 메서드의 매개변수를 전부 가져올 수 있습니다.

이를 통해서 Controller 메서드에서 HttpServletRequest를 매개변수로 받고

joinPoint.getArgs()를 통해서 사용을 하면 됩니다.

 

하지만 그러면 필요한 메서드마다 전부 HttpServletRequest를 매개변수로 받아야 하게 됩니다.

대신 인터셉터나 필터를 이용해도 되지만 다른 방법이 있지 않을까 해서 검색을 해봤더니 방법이 있었습니다.

 

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();

이렇게 사용을 하면 AOP에서도 HttpServletRequest와 HttpServletResponse를 사용할 수 있습니다.

 

 

ServletRequestAttributes는 HttpRequest 가 오는 경우, RequestContextListener.requestInitialized(ServletRequestEvent requestEvent) 함수에 의해 값이 전달되기 때문에 값을 받을 수 있다고 합니다.

 

참고

https://whitelife.tistory.com/214

 

감사합니다.