问题:在使用Thymeleaf模板时,某些地方需要使用全局变量,即在Java中一处赋值,在任何页面均可获取。
解决方法:
@Resource
private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) {
println("configureThymeleafStaticVars 配置thymeleaf静态变量");
if(viewResolver != null) {
Map<String, Object> vars = new HashMap<>();
vars.put("var", "Hello World");
viewResolver.setStaticVariables(vars);
}
}
改进:
@Resource(name="thymeleafViewResolver")
ThymeleafViewResolver thymeleafViewResolver;
//添加全局静态变量
if (thymeleafViewResolver != null) {
Map<String, Object> vars = new HashMap<>();
vars.put("shirouser", principal);
thymeleafViewResolver.setStaticVariables(vars);
}
在任何html中均可使用此变量
<a href="#" th:if="${shirouser} != null" ><span th:text="${shirouser.nickname}"></span></a>
测试此法可行,但尚未知是否会产生其他问题。