Reputation: 1059
I have a spring project set up with thymeleaf and thymeleaf-layout-dialect.
In this project I have a controller
@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";
}
}
I also have a layout
...
<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>
and two views: home.html and info.html which have different unique contents
<!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>
and a header
<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>
I'd like to print the username in the header without passing it as an attribute on the model in the controller methods. So, Can I run some custom java code before the header is included to find out the username regardless of what controller method is beeing used? What options do I have?
Upvotes: 2
Views: 4119
Reputation: 15992
If you would use Spring Security in combination with the Thymeleaf Spring Security module, you can do the following:
<span class="user-info">
<small>Welcome,</small>
<span sec:authentication="principal">Username</span>
</span>
If you don't want to use Spring Security, you can write a custom dialect/processor which inserts the username for you.
Upvotes: 1