Tips

Request Body 의 λ‚΄μš©μ„ μž¬μ‚¬μš© ν•˜κ³  μ‹Άμ„κ²½μš°

POST λ°©μ‹μœΌλ‘œ μ „λ‹¬λ˜λŠ” application/json νƒ€μž…μ˜ 데이터λ₯Ό Servlet 의 Filter λ‚˜ Spring 의 Interceptor μ—μ„œ λͺ¨μ’…μ˜ 처리λ₯Ό ν•˜κΈ° μœ„ν•΄μ„œλŠ” HttpServletRequest 의 InputStream 을 읽어듀여야 ν•˜λŠ” κ²½μš°κ°€ μžˆλ‹€.

λ§Œμ•½ HttpServletRequest μ—μ„œ InputStream 을 ν•œλ²ˆ 읽으면 λ‹€μ‹œλŠ” 읽을 수 μ—†κΈ° λ•Œλ¬Έμ— RequestWrapper 객체λ₯Ό λ§Œλ“€μ–΄ InputStream 을 μž„μ‹œλ‘œ μ €μž₯ν•˜λŠ” ν˜•νƒœλ‘œ μ‚¬μš©ν•΄μ•Ό ν•œλ‹€.

Spring MVC Request Life Cycle

이 방식은 Filter λ₯Ό μ΄μš©ν•˜λŠ” λ°©μ‹μœΌλ‘œ λΉ„μŠ·ν•œ λ°©μ‹μ˜ λ™μž‘μΈ Interceptor μ™€λŠ” 차이점이 μžˆλ‹€.

Filter 와 Interceptor 의 차이점

μ•„λž˜λŠ” μ‹€μ œλ‘œ μ μš©ν–ˆλ˜ 방법이닀.

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(requestFilter());
        // ν•„ν„° 등둝
        bean.addUrlPatterns(("/*"));

        return bean;
    }
    @Bean(name = "requestFilter")
    public Filter requestFilter() {
        return new RequestFilter();
    }
}
@Component
public class RequestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        RequestWrapper wrapper = new RequestWrapper(req);
        chain.doFilter(wrapper, response);
    }

    @Override
    public void destroy() { }
}
public class RequestWrapper extends HttpServletRequestWrapper {
    private byte[] bytes;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // InputStream 을 byte μ½”λ“œλ‘œ λ§Œλ“¬
        bytes = IOUtils.getBytes(super.getInputStream());
    }

    public ServletInputStream getInputStream() {
        final ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        return new ServletInputStreamImpl(bis);
    }
}