后端接口,經常會用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 "";
}
}