Filter 란?

JangUT·2025년 3월 4일

📌 Filter 란 ?

Filter는 클라이언트의 요청과 응답을 가로채어 특정한 처리를 할 수 ㅇㅆ는 기능을 제공합니다. 주로 Servlet Container 수준에서 동작하여, 요청이 DispatcherServlet에 도달하기 전이나 응답이 클라이언트에 전달되기 전에 필요한 작업을 수행합니다.


📌 Filter 의 동작 흐름

  • request

    • Client가 Server로 HTTP 요청을 보냅니다.
    • WAS (Web Application Server) 가 요청을 받아들입니다.
    • 등록된 Filter들이 순서대로 요청을 처리합니다.
    • DispatcherServlet으로 요청이 전달됩니다.
    • 이후 Controller에서 비즈니스 로직을 수행합니다.
  • response

    • Controller에서의 처리가 끝나면 응답이 생성됩니다.
    • Filter들이 response에서 필요한 처리를 합니다.
    • WAS들 거쳐 클라이언트에게 응답이 전달됩니다.

📌Filter 인터페이스

public interface Filter {
    default void init(FilterConfig filterConfig) throws ServletException {}
    void doFilter(ServletRequest request, ServletResponse response, FilterChain 	chain)
        throws IOException, ServletException;
    default void destroy() {}
}
  • init() : 필터 초기화 메서드로, 필터가 생성될 때 한 번 호출됩니다.
  • doFilter() : 필터의 핵심 로직을 수행하며, 모든 요청에 대해 호출됩니다.
  • destroy() : 필터가 제거될 때 호출되어 자원을 해제합니다.

📌doFilter() 메서드의 동작

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    // 전처리 로직
    chain.doFilter(request, response);
    // 후처리 로직
}	
  • 전처리 로직 : chain.doFilter() 호출 전에 실행되며, 요청을 가로채어 필요한 작업을 수행합니다.

  • 후처리 로직 : chain.doFilter() 호출 후에 실행되며, 응답에 대한 처리를 수행합니다.


📌 Filter의 실제 사용 예제

  • 보안 및 인증/인가 처리 : 모든 요청에 대해 인증 토큰이 유효한지 검사
  • 로깅 : 요청 및 응답 정보를 기록하여 모니터링
  • 데이터 압축 : 응답 데이터를 압축하여 전송 효율성 향상
  • 인코딩 처리 : 요청 및 응답에 대한 문자 인코딩 설정

📌 Filter의 구현 단계

1. 필터 클래스 생성

public class LoginCheckFilter implements Filter {

    private static final String[] WHITE_LIST = {"/login", "/signup", "/resources/*"};

    @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 {
            if (needsAuthentication(requestURI)) {
                HttpSession session = httpRequest.getSession(false);
                if (session == null || session.getAttribute("USER") == null) {
                    httpResponse.sendRedirect("/login?redirectURI=" + requestURI);
                    return;
                }
            }
            chain.doFilter(request, response);
        } catch (Exception e) {
            throw e;
        }
    }

    private boolean needsAuthentication(String requestURI) {
        return !Arrays.stream(whiteList).anyMatch(requestURI::startsWith);
    }
}

  • 화이트리스트 : 인증이 필요 없는 URL패턴을 정의합니다.
  • 인증 체크 로직 : 세션에 사용자 정보가 없으면 로그인 페이지로 리다이렉트합니다.

2. 필터 등록


public class FilterConfig {

	@Bean
    public FilterRegistrationBean<LoginCheckFilter> loginCheckFilter() {
    	
        FilterRegistrationBean<LoginCheckFilter> registrationBean = new FilterRegistrationBean<>();
        
        // 등록할 필터 객체를 설정 (LoginCheckFilter를 필터로 사용)
        registrationBean.setFilter(new LoginCheckFilter()); 
        
        // 필터의 순서를 지정 (값이 낮을수록 먼저 실행됨)
        registrationBean.setOrder(1);
        
        // 필터를 적용할 URL 패턴을 설정 ("/*" 는 모든 요청에 대해 필터를 적용)
        registrationBean.addUrlPatterns("/*");
        
        
        // 필터 설정을 반환하여 스프링 컨테이너에 등록
        return registrationBean;
  • FilterRegistrationBean 을 통해 필터를 Spring 컨텍스트에 등록합니다.
  • setOrder(1): 필터의 실행 순서를 지정합니다.
profile
평범한 개발자

0개의 댓글