본문 바로가기

개발기술/Web Dev

서블릿 - Interception , Filter

서블릿 Filter

Servlet Filter is an object that can intercept and manipulate requests and responses in a web application. "filter" specifically refers to the interception and processing of HTTP requests and responses within the web application framework. (interception is a broader concept than filter)

 

Key Concepts of Servlet Filters:

  1. Interception Mechanism: Filters work by intercepting requests before they reach the servlet and responses before they are sent back to the client. This allows filters to modify or examine the incoming request and the outgoing response. They operate as part of the request/response pipeline rather than through object substitution(proxy pattern)
  2. Chain of Filters: Multiple filters can be configured to work in sequence. This is known as a filter chain
  3. Filter Interface: To create a filter, you implement the javax.servlet.Filter interface, which requires the implementation of three methods:
    • init(FilterConfig filterConfig): Initializes the filter, typically used to read configuration parameters.
    • doFilter(ServletRequest request, ServletResponse response, FilterChain chain): The core method that performs the filtering task. It can modify the request/response and then pass them on by invoking chain.doFilter(), or it can stop the request from proceeding further.
    • destroy(): Cleans up resources when the filter is taken out of service.

 

필터의 적용

PureJava - filters are registered in the web.xml file, which is the standard deployment descriptor for web applications.

<filter>
    <filter-name>logFilter</filter-name>
    <filter-class>com.example.LogFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>logFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

Spring - @Componenet등록을 통해서 빈으로 만들면 자동으로 동작시키게 끔한다

@Slf4j
@Component
public class LogFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse
            , FilterChain filterChain) throws IOException, ServletException {
        // 외부 -> filter( -> 처리) filter -> 외부
        log.info("Hello LogFilter"+Thread.currentThread());
        filterChain.doFilter(servletRequest,servletResponse);
        log.info("Bye LogFilter"+Thread.currentThread());
    }
}

 

Spring 다수의 필터 - @Configuration 클래스를 통해서 FilterRegistrationBean에 담고 이들의 순서, URL 맵핑 등 좀더 구체적인 Cutomization을 실행할 수 있다.

@Configuration
public class WebConfig {

    @Bean
    FilterRegistrationBean<Filter> LoggingFilter() {
        FilterRegistrationBean<Filter> filterRegistrationBean =
                new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new LogFilter());
        filterRegistrationBean.setOrder(1);
        filterRegistrationBean.addUrlPatterns("/*");

        return filterRegistrationBean;
    }
}

 

서블릿 Interception 

interception is a mechanism used to allow additional behavior to be inserted into the execution of methods or lifecycle events in an object-oriented system. interceptors in Java EE (Jakarta EE) and Aspect-Oriented Programming (AOP) in frameworks like Spring often use the proxy pattern to implement interception. The proxy pattern is a structural design pattern that involves creating a surrogate or placeholder object that controls access to another object, typically to add some additional behavior before or after the actual method invocation.