如何在模板上下文中添加“全局”变量(如用户名)?
目前,我将这些显式设置为我的TemplateController中的每个ModelAndView对象。
几种方法可以做到这一点。
如果要向单个控制器提供的所有视图添加变量,可以添加@ModelAttribute
带注释的方法 - see reference doc。
请注意,您也可以使用相同的@ModelAttribute
机制一次寻址多个控制器。为此,您可以在使用@ModelAttribute
-@ControllerAdvice
注释的类中实现该see reference doc方法。
@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());
}
}
如果你只是想从你的application.properties
到你的thymeleaf
模板,那么你可以使用Spring的SpEL。
${@environment.getProperty('name.of.the.property')}
您可能希望查看@ModelAttribute。 http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
Blockquote在Thymeleaf中,可以使用以下语法访问这些模型属性(或Thymeleaf术语中的上下文变量):$ {attributeName},其中attributeName在我们的例子中是消息。这是一个Spring EL表达式。