How can I add a "global" variable such as username to be used all around my template context?
Currently I am setting these explicitly to each ModelAndView object in my TemplateController.
How can I add a "global" variable such as username to be used all around my template context?
Currently I am setting these explicitly to each ModelAndView object in my TemplateController.
Several ways to do this.
If you want to add a variable to all views served by a single controller, you can add a @ModelAttribute
annotated method - see reference doc.
Note that you can also, using the same @ModelAttribute
mechanism, address multiple Controllers at once. For that, you can implement that @ModelAttribute
method in a class annotated with @ControllerAdvice
- see reference doc.
@ControllerAdvice
work for me:
@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());
}
}
If you simply want something from your application.properties
into your thymeleaf
template, then you can make use of Spring's SpEL.
${@environment.getProperty('name.of.the.property')}
You may like to have look at @ModelAttribute. http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
Blockquote In Thymeleaf, these model attributes (or context variables in Thymeleaf jargon) can be accessed with the following syntax: ${attributeName}, where attributeName in our case is messages. This is a Spring EL expression.
Here is an example for Spring Boot and Thymeleaf.
First, we need to create a @ControllerAdvice
:
@ControllerAdvice
public class MvcAdvice {
// adds a global value to every model
@ModelAttribute("baseUrl")
public String test() {
return HttpUtil.getBaseUrl();
}
}
Now, we have access to baseUrl
in our templates:
<span th:text=${baseUrl}></span>
Wanted to give a code sample as per accepted answer from Brian Clozel:
@ControllerAdvice(annotations = Controller.class)
public class GetPrincipalController {
@ModelAttribute("principal")
public Object getCurrentUser() {
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
After above, you will get an object of principal and then you can use everything from that object "GLOBALLY" in your application, in any of your Thyemleaf Template like this:
<li><span th:text="${principal.getUsername()}"></span></li>
<li><span th:text="${principal.getAuthorities()}"></span></li>
© 2022 - 2024 — McMap. All rights reserved.