본문 바로가기

java/spring

Spring Filter

package com.example.filter;

import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/api/*")
public class AllFilter  implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 전
        ContentCachingRequestWrapper wrappingRequest = new ContentCachingRequestWrapper((HttpServletRequest)request);
        ContentCachingResponseWrapper wrappingResponse = new ContentCachingResponseWrapper((HttpServletResponse) response);

        chain.doFilter(request, response);

        // 후
        wrappingResponse.copyBodyToResponse();

    }

    @Override
    public void destroy() {
        System.out.println("destory");
    }
}

*키워드

doFilter
copyBodyToResponse
WebFilter
반응형

'java > spring' 카테고리의 다른 글

Spring AOP ( annotation 활용)  (0) 2022.04.07
Spring Exception  (0) 2022.04.07