Reputation: 4282
How can I intercept controller methods in Spring MVC and fiddle around with the given parameters passed by the Spring framework?
Example
@PostMapping(consumes = "multipart/form-data")
public ResponseEntity<?> createPerson( CreatePersonCommand command ) {
// ...
}
I want to be able to fiddle with the command object before my createPerson method is called. Lets say, because I want to set additional parameters (e.g. timestamp,...)
Update:
I am aware of the HandlerIntercaptor & Adapter. However, I still dont know how can I fiddle around with the CreatePersonCommand object in the preHandle Method.
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse response, Object handler )
throws Exception {
// FIDDLE WITH CreatePersonCommand ???
return true;
}
Upvotes: 1
Views: 2794
Reputation: 5948
With Spring you could use aspects, and easy example for your case would be this:
@Aspect
@Component
public class PreHandlerAspect {
@Before("execution(* com.your.controller..*Controller.*(..))")
public void beforeController(JoinPoint joinPoint){
//Here your code
//You could access to the request, parameters, add the aspect for just 1 controller, many,...
}
}
Upvotes: 2
Reputation: 2301
You can use Interceptors, method preHandle()
:
https://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/
Update: I don't know how to do it exactly but you can try to use your handler object:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
((HandlerMethod)handler).getMethodParameters()...
}
Let me know your final solution :)
Upvotes: 2