前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >场景:当所有的 Controller,都需要传入某个参数,代码如何写?

场景:当所有的 Controller,都需要传入某个参数,代码如何写?

原创
作者头像
水货程序员
发布2019-06-11 10:29:40
1.2K0
发布2019-06-11 10:29:40
举报
文章被收录于专栏:javathingsjavathings

假设有个场景,每一个 controller 都需要接收一个共同的参数,那么除了在每一个方法中都加入这个参数之外,还有一个方法就是使用@ControllerAdvice 注解。

@ControllerAdvice 参数之前的文章(http://www.javathings.top/springboot 中异常处理/)提到过,用于全局的处理异常。

@ControllerAdvice 和@ModelAttribute 注解配合使用,可以实现全局的 Controller 都接收到同一个 Model。举个例子:

代码语言:java
复制
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,都需要传入某个参数,代码如/

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档