Tips
Request Body μ λ΄μ©μ μ¬μ¬μ© νκ³ μΆμκ²½μ°
POST λ°©μμΌλ‘ μ λ¬λλ application/json
νμ
μ λ°μ΄ν°λ₯Ό Servlet μ Filter λ Spring μ Interceptor μμ λͺ¨μ’
μ μ²λ¦¬λ₯Ό νκΈ° μν΄μλ HttpServletRequest μ InputStream μ μ½μ΄λ€μ¬μΌ νλ κ²½μ°κ° μλ€.
λ§μ½ HttpServletRequest μμ InputStream
μ νλ² μ½μΌλ©΄ λ€μλ μ½μ μ μκΈ° λλ¬Έμ RequestWrapper
κ°μ²΄λ₯Ό λ§λ€μ΄ InputStream μ μμλ‘ μ μ₯νλ ννλ‘ μ¬μ©ν΄μΌ νλ€.
μ΄ λ°©μμ 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);
}
}
β Batch