Home > Blockchain >  Is there a way to provide an attribute to all models in Spring?
Is there a way to provide an attribute to all models in Spring?

Time:01-12

Thymeleaf dropped template expressions like #session, #httpServletRequest etc. in Version 3.1 (https://www.thymeleaf.org/doc/articles/thymeleaf31whatsnew.html).

We used those a lot in relatively large applications. I wrote an interceptor to populate those attributes at every request since I don't want to add them in every Controller needed (like described in the migration guide).

Does anybody know a better way of achieving this?

CodePudding user response:

This is already the best method to populate attributes at each request, compared to the earlier methods defined in the Spring framework documentations.

CodePudding user response:

I learned that @ControllerAdvice can be used in this case (see https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc).

Classes annotated with @ControllerAdvice, can have methods annotated with @ModelAttribute to populate attributes over multiple Controllers (all of them if not specified otherwise).

In my case:

@ControllerAdvice
public class CommonDataAdvice {
     @Autowired
     private HttpServletRequest request;

     @ModelAttribute("request")
     public HttpServletRequest populateRequest(){
           return request;
     }
}
  • Related