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

问题描述 投票:16回答:4

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

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

java spring-mvc thymeleaf
4个回答
14
投票

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

如果要向单个控制器提供的所有视图添加变量,可以添加@ModelAttribute带注释的方法 - see reference doc

请注意,您也可以使用相同的@ModelAttribute机制一次寻址多个控制器。为此,您可以在使用@ModelAttribute -@ControllerAdvice注释的类中实现该see reference doc方法。


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());
     }
  }

4
投票

如果你只是想从你的application.properties到你的thymeleaf模板,那么你可以使用Spring的SpEL

${@environment.getProperty('name.of.the.property')}

1
投票

您可能希望查看@ModelAttribute。 http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

Blockquote在Thymeleaf中,可以使用以下语法访问这些模型属性(或Thymeleaf术语中的上下文变量):$ {attributeName},其中attributeName在我们的例子中是消息。这是一个Spring EL表达式。

© www.soinside.com 2019 - 2024. All rights reserved.