在Spring过滤器中更改HttpServletRequest的POST主体

时间:2016-06-18 18:41:53

标签: java spring filter

我有一个Spring过滤器:

  public class MyFilter implements Filter {

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

       }
  }

现在,如果此请求是POST,我想在请求到达我的控制器之前编写/修改请求的POST主体。有没有办法可以做到这一点?我环顾四周,可以找到关于如何阅读身体的大量信息,但不能写出

1 个答案:

答案 0 :(得分:0)

There is one more option but don't know whether it fits into your requirement. Maybe it can help you out. The below approach is using Spring AspectJ. Make changes in the below code according to your need.

@Component
@Aspect
public class WebServiceAPILoggingAspect {

    private static Logger logger = Logger.getLogger(WebServiceAPILoggingAspect.class);

    @Before("execution(* com.progress.d2c.web.service.*.controller.*.*(..))")
    public Object controllerMethodsAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceedResponse = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String payload = IOUtils.toString(request.getInputStream(), "UTF-8");
        // Now write your code...
        try {
            proceedResponse = joinPoint.proceed();
        } catch (Exception e) {
            logger.error("Failed to complete the operation.");
            throw e;
        }
        return proceedResponse;
    }
}