How to modify request body before reaching controller in spring boot

后端 未结 5 1032
野的像风
野的像风 2020-12-08 12:11

I have a spring boot application. I change the request body of every post request. Is it possible to modify the request body before the request reaches the controller. Pleas

5条回答
  •  眼角桃花
    2020-12-08 12:52

    One way to this is by reflection. ProceedingJoinPoint contains the args object passed to method

    @Aspect
    @Component
    public class AopInterceptor {
    
        @Around(value = "@annotation(xyz.rpolnx.spring.web.poc.annotation.AopIntercepExample)")
        public Object handler(final ProceedingJoinPoint joinPoint) throws Throwable {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    
            Object[] args = joinPoint.getArgs();
    
            Class someClass = args[0].getClass();
    
            Field field = someClass.getDeclaredField("custom");
            field.setAccessible(true);
            field.set(args[0], "custom");
            field.setAccessible(false);
    
            return joinPoint.proceed();
        }
    }
    
    @RestController
    public class SimpleController {
    
        @PostMapping("/aop")
        @AopIntercepExample
        public Person handleAopIntercept(@RequestBody Person nodes) {
            return nodes;
        }
    }
    
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AopIntercepExample {
    }
    
    public class Person {
        private String name;
        private String id;
        private String custom;
    }
    

提交回复
热议问题