728x90
1. 서블릿 필터
공통 관심 사항
- 요구사항을 보면 로그인 한 사용자만 상품 관리 페이지에 들어갈 수 있어야 한다.
- 문제는 로그인 하지 않은 사용자도 다음 URL을 직접 호출하면 상품 관리 화면에 들어올 수 있다.
공통 관심사는 AOP로 해결할 수 있지만, 웹과 관련된 공통 관심사는 서블릿 필터 또는 스프링 인터셉터를 사용하는 것이 좋다.
1) 서블릿 필터 소개
필터는 서블릿이 지원하는 수문장이다.
필터 흐름
HTTP 요청 → WAS → 필터 → 서블릿 → 컨트롤러
필터 제한
HTTP 요청 → WAS → 필터 → 서블릿 → 컨트롤러 // 로그인 사용자
HTTP 요청 → WAS → 필터(적절하지 않은 요청이라 판단, 서블릿 호출 X) // 비 로그인 사용자
필터 인터페이스
- init(): 필터 초기화 메소드, 서블릿 컨테이너가 생성될 때 호출된다.
- doFilter(): 고객의 요청이 올 때마다 해당 메서드가 호출된다. 필터의 로직을 구현
- destory(): 필터 종료 메소드, 서블릿 컨테이너가 종료될 때 호출된다.
public interface Filter {
public default void init(FilterConfig filterConfig) throws ServletException
{}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException;
{}
public default void destroy() {}
}
2) 서블릿 필터 - 요청 로그
WebConfig - 필터 설정
- setFilter(new LogFilter()) : 등록할 필터를 지정한다.
- setOrder(1) : 필터는 체인으로 동작한다. 따라서 순서가 필요하다. 낮을 수록 먼저 동작한다.
- addUrlPatterns("/*") : 필터를 적용할 URL 패턴을 지정한다. 한번에 여러 패턴을 지정할 수 있다.
@Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean logFilter() {
FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new LogFilter());
filterRegistrationBean.setOrder(1);
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
3) 서블릿 필터 - 인증 체크
@Slf4j
public class LoginCheckFilter implements Filter {
private static final String[] whitelist = {"/", "/members/add", "/login", "/logout","/css/*"};
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String requestURI = httpRequest.getRequestURI();
try {
log.info("인증 체크 필터 시작 {}", requestURI);
if (isLoginCheckPath(requestURI)) {
log.info("인증 체크 로직 실행 {}", requestURI);
HttpSession session = httpRequest.getSession(false);
if (session == null ||
session.getAttribute(SessionConst.LOGIN_MEMBER) == null) {
log.info("미인증 사용자 요청 {}", requestURI);
//로그인으로 redirect
httpResponse.sendRedirect("/login?redirectURL=" + requestURI);
return; // 미인증 사용자는 다음으로 진행하지 않고 끝!
}
}
chain.doFilter(request, response);
} catch (Exception e) {
throw e; //예외 로깅 가능 하지만, 톰캣까지 예외를 보내주어야 함
} finally {
log.info("인증 체크 필터 종료 {}", requestURI);
}
}
/**
* 화이트 리스트의 경우 인증 체크X
*/
private boolean isLoginCheckPath(String requestURI) {
return !PatternMatchUtils.simpleMatch(whitelist, requestURI);
}
}
2. 스프링 인터셉터
1) 스프링 인터셉터 소개
스프링 인터셉터도 서블릿 필터와 같이 웹과 관련된 공통 관심 사항을 해결할 수 있는 기술이다.
스프링 인터셉터는 스프링 MVC가 제공하는 기술이다.
2) 스프링 인터셉터 흐름
- 스프링 인터셉터는 디스패처 서블릿과 컨트롤러 사이에서 컨트롤러 호출 직전에 호출 된다.
- 스프링 MVC의 시작점이 디스패처 서블릿이라고 생각하면 이해가 된다.
- 스프링 인터셉터에서도 URL 패턴을 적용할 수 있는데, 서블릿 URL 패턴과는 다르고 정밀하게 설정 가능하다.
HTTP 요청 → WAS → 필터 → 서블릿 → 스프링 인터셉터 → 컨트롤러
HTTP 요청 → WAS → 필터 → 서블릿 → 스프링 인터셉터(적절하지 않은 요청, 컨트롤러 호출 X)
3) 스프링 인터셉터 체인
- 스프링 인터셉터는 체인으로 구성이 된다.
- 중간에 인터셉터를 자유롭게 추가할 수 있다.
HTTP 요청 → WAS → 필터 → 서블릿 → 인터셉터1 → 인터셉터2 → 컨트롤러
4) 스프링 인터셉터 인터페이스
- preHandle: 인터셉터는 컨트롤러 호출 전
- preHandle 의 응답값이 true 이면 다음으로 진행하고, false 이면 더는 진행하지 않는다.
- postHandle: 컨트롤러 호출 후에 호출된다.
- afterCompletion: 뷰가 렌더링 된 이후에 호출된다.
- handler: 어떤 컨트롤러가 호출되는지 호출 정보도 받을 수 있다.
- modelAndView: 어떤 모델이 반환되는지 응답 정보도 받을 수 있다.
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
5) 스프링 인터셉터 예외
- preHandle : 컨트롤러 호출 전에 호출된다.
- postHandle : 컨트롤러에서 예외가 발생하면 postHandle 은 호출되지 않는다.
- afterCompletion : afterCompletion 은 항상 호출된다. 이 경우 예외( ex )를 파라미터로 받아서 어떤 예외가 발생했는지 로그로 출력할 수 있다.
6) 스프링 인터셉터 - 요청 로그
- HandlerMethod
- 핸들러 정보는 어떤 핸들러 매핑을 사용하는가에 따라 달라진다.
- 스프링을 사용하면 일반적으로@Controller , @RequestMapping 을 활용한 핸들러 매핑을 사용하는데, 이 경우 핸들러 정보로 HandlerMethod 가 넘어온다.
- ResourceHttpRequestHandler
- @Controller 가 아니라 /resources/static 와 같은 정적 리소스가 호출 되는 경우, ResourceHttpRequestHandler 가 핸들러 정보로 넘어오기 때문에 타입에 따라서 처리가 필요하다.
- postHandle, afterCompletion
- 종료 로그를 postHandle 이 아니라 afterCompletion 에서 실행한 이유는, 예외가 발생한 경우
postHandle 가 호출되지 않기 때문이다. - afterCompletion 은 예외가 발생해도 호출 되는 것을 보장한다.
- 종료 로그를 postHandle 이 아니라 afterCompletion 에서 실행한 이유는, 예외가 발생한 경우
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogInterceptor())
.order(1)
.addPathPatterns("/**")
.excludePathPatterns("/css/**", "/*.ico", "/error");
registry.addInterceptor(new LoginCheckInterceptor())
.order(2)
.addPathPatterns("/**")
.excludePathPatterns("/", "/members/add", "/login", "/logout", "/css/**", "/*.ico", "/error");
}
}
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
public static final String LOG_ID = "logId";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
String uuid = UUID.randomUUID().toString();
request.setAttribute(LOG_ID, uuid);
//@RequestMapping: HandlerMethod
//정적 리소스: ResourceHttpRequestHandler
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler; //호출할 컨트롤러 메서드의 모든 정보가 포함되어 있다.
}
log.info("REQUEST [{}][{}][{}]", uuid, requestURI, handler);
return true; //false 진행X
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle [{}]", modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
String requestURI = request.getRequestURI();
String logId = (String)request.getAttribute(LOG_ID);
log.info("RESPONSE [{}][{}]", logId, requestURI);
if (ex != null) {
log.error("afterCompletion error!!", ex);
}
}
}
'온라인 강의 > Spring Framework' 카테고리의 다른 글
[강의] 스프링 MVC 2편 - 예외 처리와 오류 페이지(섹션8) (0) | 2024.06.15 |
---|---|
[스프링 MVC 1편] 웹 페이지 만들기 (0) | 2024.06.09 |
[스프링 MVC 1편] 구조 이해 (0) | 2024.05.25 |
[스프링 MVC 1편] MVC 프레임워크 만들기 (0) | 2024.05.19 |
[스프링 MVC 1편] 서블릿, JSP, MVC 패턴 (0) | 2024.05.11 |