Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add attributes to the model of all controllers in Spring 3

Every single view in my Spring 3 app has a set of attributes they can rely on. So the first line of every controller is something like:

ControllerHelper.addDefaultModel(model, personManager, request); 

In there I'll add

  • user object and full name retrieved from the database if person is logged in
  • set of variables which are typically set once (e.g. imagesHost)
  • set of languages a visitor can switch to
  • current language
  • some statistics (e.g. total # of people in our system)

This all allows each view to display the logged in user's name, easily reference an image location, a list of languages and some overall stats about the site.

So the question is, is the controller model object the best place to store all the data or is there a more convenient place which makes it just as easy for views to access this info?

And secondly, I'd REALLY love not to have to have the ControllerHelper line above as the first line in every controller. It's actually not always the first line, sometimes I first check if I need to redirect in that controller, because I don't want to waste resources filling the model for no reason. Maybe a filter or annotation or some Spring callback mechanism could make sure the ControllerHelper code is called after the controller is finished but right before the view is rendered, skipping this if a redirect was returned?

like image 287
at. Avatar asked Sep 09 '11 11:09

at.


People also ask

What is used to add attributes in a model in Spring boot?

Model , ModelMap , and ModelAndView are used to define a model in a Spring MVC application. Model defines a holder for model attributes and is primarily designed for adding attributes to the model. ModelMap is an extension of Model with the ability to store attributes in a map and chain method calls.

Which is used to add attributes in a model?

The Spring Model is an interface in Spring that is used to add attributes to the model.

What is difference between @RequestBody and @ModelAttribute?

@ModelAttribute is used for binding data from request param (in key value pairs), but @RequestBody is used for binding data from whole body of the request like POST,PUT.. request types which contains other format like json, xml.

What are model attributes in Spring?

In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object. So let's understand the whole concept of @ModelAttribute Annotation with an interesting example project.


1 Answers

You could write an org.springframework.web.servlet.HandlerInterceptor. (or its convenience subclass HandlerInterceptorAdapter)

@See: Spring Reference chapter: 15.4.1 Intercepting requests - the HandlerInterceptor interface

It has the method:

void postHandle(HttpServletRequest request,                 HttpServletResponse response,                 Object handler,                 ModelAndView modelAndView) throws Exception; 

This method is invoked after the controller is done and before the view is rendered. So you can use it, to add some properties to the ModelMap

An example:

/**  * Add the current version under name {@link #VERSION_MODEL_ATTRIBUTE_NAME}  * to each model.   * @author Ralph  */ public class VersionAddingHandlerInterceptor extends HandlerInterceptorAdapter {      /**      * The name under which the version is added to the model map.      */     public static final String VERSION_MODEL_ATTRIBUTE_NAME =                 "VersionAddingHandlerInterceptor_version";      /**              *  it is my personal implmentation       *  I wanted to demonstrate something usefull      */     private VersionService versionService;      public VersionAddingHandlerInterceptor(final VersionService versionService) {         this.versionService = versionService;     }      @Override     public void postHandle(final HttpServletRequest request,             final HttpServletResponse response, final Object handler,             final ModelAndView modelAndView) throws Exception {          if (modelAndView != null) {             modelAndView.getModelMap().                   addAttribute(VERSION_MODEL_ATTRIBUTE_NAME,                                versionService.getVersion());         }     } } 

webmvc-config.xml

<mvc:interceptors>     <bean class="demo.VersionAddingHandlerInterceptor" autowire="constructor" /> </mvc:interceptors> 
like image 127
Ralph Avatar answered Sep 19 '22 12:09

Ralph