Announcement Announcement Module
No announcement yet.
Automatically assign variables to ModelMap Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Automatically assign variables to ModelMap

    I have an action controller with three separate actions. Each actions loads a different base template. I am using Freemarker as a template engine.

    Despite being three separate pages, they have common parameters. Right now each action method are passing those parameters to the ModelMap themselves, but this seems to violate DRY.

    Is there a way to consolidate this somehow? Some way to automatically add parameters to a view?

    In this case, I need to add values from a bean directly to ModelMap so rather static values, but we also have dynamic parameters (eg, common request parameters) as well.


  • #2
    What we've done is created an additional ControllerContext class that takes in the request and response and is initialized in every controller to set common request attributes, however this has created boilerplate code for every controller. You may want to write a filter or an interceptor that can add these attributes to every request. See this StackOverflow post for details but basically you would extend HandlerInterceptorAdapter (see Spring docs for reference)

     * 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 =
         *  it is my personal implmentation 
         *  I wanted to demonstrate something usefull
        private VersionService versionService;
        public VersionAddingHandlerInterceptor(final VersionService versionService) {
            this.versionService = versionService;
        public void postHandle(final HttpServletRequest request,
                final HttpServletResponse response, final Object handler,
                final ModelAndView modelAndView) throws Exception {
            if (modelAndView != null && modelAndView.getModelMap() != null) {
        <bean class="demo.VersionAddingHandlerInterceptor" autowire="constructor" />