SpringBoot 全局处理以及注入请求参数

后端接口,经常会用token获取对应的账号信息。于是考虑将这个步骤封装起来。
之前项目使用ThreadLocal去做这样的事情,但昨天看SpringBoot的官方文档,发现借助框架的功能也可以做这样的事情,而且更方便,直观

@ModelAttribute 介绍

FOR EXAMPLE:

@RestController
public class TestController {
    @ModelAttribute
    public String add(){
        return "哈哈";
    }
    @RequestMapping("hello")
    public String hello(@ModelAttribute String haha){
        return haha;
    }
}

被@ModelAttribute注释的add()方法会在此controller每个方法执行前被执行,add()被ModelAttribute注解的方法的返回值可以在此controller的RequestMapping方法中获取到。
因此,可以利用@ModelAttribute注解封装需要在Controller之前进行处理的步骤

@ControllerAdvice 介绍

通常,@ExceptionHandler、@InitBinder和@ModelAttribute注解的方法声明在Controller类中。
如果希望这些注解能更全局的应用,那么就可以把这些方法声明在@ControllerAdvice或者@RestControllerAdvice中。

因此,可以用@ControllerAdvice和@ModelAttribute去全局处理token

具体实现

全局处理:

@ControllerAdvice
public class LoginRegisterHandle {

    @Autowired
    private UserService userService;

    @ModelAttribute
    public UserInfo registerUserInfo(HttpServletRequest request){
        // 检测有没有传token,没有则返回空
        String token = request.getHeader("token");
        if(token == null || token.equals("")){
            return null;
        }
        return userService.getLoginUserInfo(token);
    }
}

使用:

@RestController
public class TestController {
    @GetMapping("hello")
    public String hello(@ModelAttribute UserInfo user){
        System.out.println(user.getId());
        return "";
    }
}

参考

  • 官网文档
    • https://docs.spring.io/spring/docs/5.0.12.RELEASE/spring-framework-reference/web.html#mvc-ann-modelattrib-method-args
    • https://docs.spring.io/spring/docs/5.0.12.RELEASE/spring-framework-reference/web.html#mvc-ann-controller-advice
  • http://www.cnblogs.com/jin-zhe/p/8241368.html

转载于:https://www.cnblogs.com/virde/p/springboot_global_attribute.html

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值