Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices around setting global model attributes in Spring MVC?

I have a menu that is data driven(cached) and it is a global component. I want to be able to inject the menu items for every request since every page is going to be using it. What is the best place to put it? I'm using annotation based Spring3. Best solution I can think of is using a OncePerRequestFilter and adding it there or sub-classing the Controller, but not sure how to do that with @Controller annotation.

like image 751
Art Avatar asked Jan 10 '11 21:01

Art


People also ask

Which are the correct options in Spring MVC that are used to bind the model class properties to form properties?

One of the most important Spring MVC annotations is the @ModelAttribute annotation. @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute, and then exposes it to a web view.

Can we map a request with model attribute?

Method level ModelAttribute annotation cannot be mapped directly with any request. Let's take a look at the following example for better understanding. We have 2 different methods in the above example.


1 Answers

I can think of two easy options:

Each @Controller class exposes the data as a method annotated with @ModelAttribute, e.g.

@ModelAttribute
public MyData getMyData() {
  ...
}

That's not really nice if you have multiple controllers, though. Also, this has the annoying side-effect of encoding the myData on to the URL for every redirect

I suggest instead that implement a HandlerInterceptor, and expose the data to every request that way. You can't use any annotation-lovin, but it's better separated from your business logic this way. This is similar to your OncePerRequestFilter idea, but a but more Spring-y.

like image 70
skaffman Avatar answered Sep 18 '22 12:09

skaffman