Spring Boot - 在控制器方法之间保存用户

时间:2017-03-14 14:57:43

标签: java spring spring-boot

避免在我的控制器方法中反复重复使用相同的userService DB查找的最佳方法是什么?

我正在使用带有spring-boot-starter-securityspring-boot-starter-thymeleaf的Spring Boot 1.5.2进行模板化。

我尝试为SecurityContextHolder.getContext().getAuthentication()添加一个实例变量,但它给了我一个NullPointerException。

@Controller
public class DashboardController {

    @Autowired
    private UserService userService;

    @Value("${product.name}")
    private String productName;


    @RequestMapping(value="/dashboard", method = RequestMethod.GET)
    public ModelAndView home() {
      ModelAndView modelAndView = new ModelAndView();
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      User user = userService.findUserByEmail(auth.getName());

      modelAndView.addObject("email", user.getEmail());

      modelAndView.setViewName("dashboard");

      return modelAndView;
    }

    @RequestMapping(value="/dashboard/faq", method = RequestMethod.GET)
    public ModelAndView faq(){
      ModelAndView modelAndView = new ModelAndView();
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      User user = userService.findUserByEmail(auth.getName());

      modelAndView.addObject("email", user.getEmail());
      modelAndView.addObject("productname", productName);

      modelAndView.setViewName("faq");

      return modelAndView;
   }

1 个答案:

答案 0 :(得分:2)

如果您想获得存储在会话中的用户,可以使用此注释:

@RequestMapping("/me")
public User me(@AuthenticationPrincipal User user) {
    return user;
}

如果您希望用户始终在百里香中使用,我会使用@ControllerAdvice

@ControllerAdvice(annotations = Controller.class)
public class GlobalVariablesControllerAdvice {

    @ModelAttribute("user")
    public User user() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        User user = null;
        // get user from authentication, but make sure to check for nulls

        return user;
    }

}