如何拦截Spring MVC中的控制器方法并使用Spring框架传递的给定参数进行调整?
示例
@PostMapping(consumes = "multipart/form-data")
public ResponseEntity<?> createPerson( CreatePersonCommand command ) {
// ...
}
我希望能够在调用createPerson 方法之前调整命令对象。可以说,因为我想设置其他参数(例如时间戳,......)
更新
我知道HandlerIntercaptor&amp;适配器。但是,我仍然不知道如何在 preHandle 方法中使用 CreatePersonCommand对象。
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse response, Object handler )
throws Exception {
// FIDDLE WITH CreatePersonCommand ???
return true;
}
答案 0 :(得分:1)
您可以使用拦截器,方法preHandle()
:
https://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/
<强>更新强> 我不知道该怎么做但你可以尝试使用你的处理程序对象:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
((HandlerMethod)handler).getMethodParameters()...
}
让我知道你的最终解决方案:)
答案 1 :(得分:1)
使用Spring,您可以使用方面,您的案例的简单示例将是:
@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,...
}
}