Spring MVC + Thymeleaf:向所有模板的上下文添加变量

the*_*ist 17 java spring-mvc thymeleaf

如何在模板上下文中添加"全局"变量(如用户名)?

目前,我将这些显式设置为我的TemplateController中的每个ModelAndView对象.

Bri*_*zel 15

几种方法可以做到这一点.

如果要向单个控制器提供的所有视图添加变量,可以添加带@ModelAttribute注释的方法 - 请参阅参考文档.

请注意,您也可以使用相同的@ModelAttribute 机制一次寻址多个控制器.为此,您可以@ModelAttribute在使用注释的类中实现该方法@ControllerAdvice- 请参阅参考文档.


Raj*_*gan 7

如果您只是想从你的东西application.properties变成你的thymeleaf模板,然后你可以使用Spring的的规划环境地政司

${@environment.getProperty('name.of.the.property')}
Run Code Online (Sandbox Code Playgroud)


小智 6

@ControllerAdvice 为我工作:

@ControllerAdvice(annotations = RestController.class)
public class AnnotationAdvice {

     @Autowired
     UserServiceImpl userService;

     @ModelAttribute("currentUser")
     public User getCurrentUser() {
         UserDetails userDetails = (UserDetails) 
         SecurityContextHolder.getContext()
               .getAuthentication().getPrincipal();

      return userService.findUserByEmail(userDetails.getUsername());
     }
  }
Run Code Online (Sandbox Code Playgroud)