Spring mvc 如何在thymeleaf片段中使用动态内容?
我有一个用thymeleaf和thymeleaf布局方言建立的spring项目 在这个项目中,我有一个控制器Spring mvc 如何在thymeleaf片段中使用动态内容?,spring-mvc,thymeleaf,Spring Mvc,Thymeleaf,我有一个用thymeleaf和thymeleaf布局方言建立的spring项目 在这个项目中,我有一个控制器 @Controller public class HomeController { @RequestMapping(value="/", method = RequestMethod.GET) public String showHome(Model model){ return "home"; } @RequestMappi
@Controller
public class HomeController {
@RequestMapping(value="/", method = RequestMethod.GET)
public String showHome(Model model){
return "home";
}
@RequestMapping(value="/info", method = RequestMethod.GET)
public String showInfo(Model model){
return "info";
}
}
我也有一个布局
...
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<body>
<div layout:fragment="header">
dummy header
</div>
<div layout:fragment="content">
dummy contents
</div>
</body>
</html>
。。。
假割台
虚拟内容
还有两个视图:home.html和info.html,它们具有不同的唯一内容
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layout">
<body>
<div layout:fragment="content">
unique contents
</div>
</body>
</html>
独特内容
和一个标题
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<body>
<div layout:fragment="header">
username is ${username}
</div>
</body>
</html>
用户名为${username}
我希望在标题中打印用户名,而不将其作为控制器方法中模型的属性传递。那么,在包含标题之前,我是否可以运行一些自定义java代码来查找用户名,而不管使用什么控制器方法?我有哪些选项?如果将Spring Security与模块结合使用,可以执行以下操作:
<span class="user-info">
<small>Welcome,</small>
<span sec:authentication="principal">Username</span>
</span>
欢迎
用户名
如果您不想使用Spring Security,您可以编写一个自定义方言/处理器,为您插入用户名。谢谢,这正是我想要的。我还发现,您可以使用拦截器向模型添加属性,但这种解决方案更加优雅。