roy
roy

Reputation: 97

How can i share an object between all controllers?

I'm using Spring-Boot and Thymeleaf as a template engine.

I have a web application which has a search input that is accessible in every view to anyone (the search triggers a form submission), the form has a th:object="${searchObject}" attribute and I'm using@RequestBody in my post controller to get the object.

Now, what i did so far was adding a model.addAttribute("searchObject", new SearchObject()) to every controller and it worked just fine but it made me think, what if there is a way to share an object between the whole app that i could declare once and use everywhere .. ?

So i did a little search and found out various solutions that refers to the available contexts in a spring application. Iv'e tried to implement few of them but couldn't figure out how.

So, is there any simple way of sharing an object between the whole app so it can be accessed inside thymeleaf without writing the same code in every controller?

I'm thinking it should look something like this

th:object="${#sharedObjects.getObjectByName(object)}"

Thanks.

Upvotes: 0

Views: 466

Answers (1)

James
James

Reputation: 12182

You can use a @ControllerAdvice to add a model attribute in all of your controllers:

@ControllerAdvice
public class SearchObjectModelAttributeAdvice {
    @ModelAttribute("searchObject")
    public SearchObject searchObject() {
        return new SearchObject();
    }
}

Upvotes: 2

Related Questions