Reputation: 1019
What's the best approach to avoid repeating the same userService DB lookup over and over again in my controller methods?
I'm using Spring Boot 1.5.2 with spring-boot-starter-security
and spring-boot-starter-thymeleaf
for templating.
I tried adding an instance variable for SecurityContextHolder.getContext().getAuthentication()
but it gave me a 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;
}
Upvotes: 0
Views: 951
Reputation: 7682
If you want to get at the user that is stored in the session, you can use this annotation:
@RequestMapping("/me")
public User me(@AuthenticationPrincipal User user) {
return user;
}
If you then want the user to always be available in thymeleaf I would use a @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;
}
}
Upvotes: 2