场景:当所有的 Controller,都需要传入某个参数,代码如何写?
2,996 total views, 3 views today
假设有个场景,每一个 controller 都需要接收一个共同的参数,那么除了在每一个方法中都加入这个参数之外,还有一个方法就是使用@ControllerAdvice 注解。
@ControllerAdvice 参数之前的文章(http://www.javathings.top/springboot 中异常处理/)提到过,用于全局的处理异常。
@ControllerAdvice 和@ModelAttribute 注解配合使用,可以实现全局的 Controller 都接收到同一个 Model。举个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.xxx.utils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestParam; @ControllerAdvice("com.xxx.restful") public class MyControllerAdvice { @ModelAttribute public void processParam(@RequestParam String param) { System.out.println("param="+param); } } |
MyControllerAdvice 这个类中的 processParam 方法,就实现了处理统一的 param 参数(controller 必须是在 com.xxx.restful 包中的)。
这能大大简化代码的书写,非常有用。
具体是实现和细节,还是自己手动的实现一下,加深印象。
ControllerAdvice 注解的详细文档,参考官方地址:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html
原创文章,转载请注明出处!http://www.javathings.top/场景:当所有的controller,都需要传入某个参数,代码如/