Programing/Framework
[Spring] afterCompletion 에서 annotation으로 로그 찍기
나모찾기
2016. 9. 13. 15:35
특정 컨트롤러 클래스에서만 User-Agent를 찍고 싶었다.
그래서 어노테이션을 만들고..
import java.lang.annotation.*;
/**
* Indicates that an annotated class or method for logging the User-Agent information.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface UserAgentLogging {
}
afterCompletion에서 세 번째 파라메터를 통해
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
찍을지 여부를 판단하는 private 메서드
private boolean isLogForUserAgent(Object handler) {
if (handler instanceof HandlerMethod) {
final HandlerMethod handlerMethod = (HandlerMethod) handler;
final Method method = handlerMethod.getMethod();
return method.getDeclaringClass().isAnnotationPresent(Controller.class)
|| method.isAnnotationPresent(UserAgentLogging.class);
}
return false;
}
user agent 는 request.getHeader("User-Agent") 를 통해 구한다.
HttpServletRequest
유사한 구현: http://itpsolver.com/spring-3-에서-컨트롤러-메서드controller-method-진입시-어노테이션annotation/