abt
abt

Reputation: 25

How to return a variable in every page from my Spring MVC application from the same controller method?

I want to return a model from my Spring MVC controller, which will be visible to all pages in my application.

So, I need a variable which return some user details. This is my code:

@RequestMapping(value = "/*", method = RequestMethod.GET)
public void status(Model model){
    Authentication auth = SecurityContextHolder.getContext()
            .getAuthentication();
    String username = auth.getName();
    Manager mgr = managerService.findOne(username);
    model.addAttribute("buget", mgr.getTeam().getTeamBuget());
}

And in my jsp page, i write something like this:

<li> <c:out value="${buget}" /> <span class="glyphicon glyphicon-euro"></span></li>

I want to be able to print the ${buget} in every page from my app.

So, my method don't work, nothing is appear in my pages and the biggest problem for me is that I don't get any exceptions or errors which could help me. Who can help me with some advices?

Upvotes: 2

Views: 2422

Answers (1)

Vivin Paliath
Vivin Paliath

Reputation: 95508

I'm not entirely sure what it is that you're trying to do. Do you mean that you want buget to be part of every page that you hit? If so, you have to insert it into the model. Based on your code, I'm assuming that you have the mistaken impression that status is going to be called regardless of whatever page you hit. Spring will resolve to the most-specific handler and so if you have another handler method in another controller that is more specific, Spring will use that. But even if the one you have was called, how would Spring know that it has to call the most-specific one next? So how would you add page-dependent model attributes to the model?

If you want buget to be part of every response, you can use @ControllerAdvice (see here for a blog post with more details):

@ControllerAdvice
public class BugetControllerAdvice {

    @ModelAttribute
    public void addBugetToModel(Model model) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();

        Manager mgr = managerService.findOne(username);
        model.addAttribute("buget", mgr.getTeam().getTeamBuget());
    }
}

Spring will now call this method before every handler-method in every controller. You can also take a look at the Spring Reference for more information.

Upvotes: 6

Related Questions