Spring MVC complex model population from multiple sources

后端 未结 5 2234
不思量自难忘°
不思量自难忘° 2020-12-30 09:36

Well, my question may sound a little bit fuzzy, but here it is, anyways. I\'m building a web application using Spring MVC 3.1.M1, JSP 2.1 (without Tiles, I use plain JSP tag

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 09:50

    Finally, I decided to stick with @ModelAttribute approach, despite its limitations.

    /**
     * Base class for all page controllers (i.e., not form submits)
     * @author malexejev
     * 23.03.2011
     */
    public abstract class AbstractPageController {
    
        @Autowired
        private VisitorService visitorService;
    
        @Autowired
        private I18nSupport i18nSupport;
    
        @Value("${xxx.env}")
        private String environment;
    
        /**
         * Implicit model enrichment with reference data.
         * No heavy operations allowed here, since it is executed before any handler method of 
         * all extending controllers
         */
        @ModelAttribute("appContext")
        public Map populateReferenceData(HttpServletRequest request) {
            Map dataMap = new HashMap();
    
            // FIXME some data is app-wide and constant, no need to re-create such map entries
            // I should take care about it when more reference data is added
            dataMap.put("visitorName", visitorService.getVisitorName());
            dataMap.put("env", environment);
            dataMap.put("availableLanguages", i18nSupport.getAvailableLanguages());
            dataMap.put("currentPath", request.getPathInfo() != null ? request.getPathInfo() : request.getServletPath());
    
            return Collections.unmodifiableMap(dataMap);
        }
    
    }
    

    This way i can get data in views via ${appContext.visitorName}. It allows me to switch transparently to Spring bean implementation (see No 3 in my answer above, @Component("headerContext") ) in case of any future problems with @ModelAttributes.

    Thanks all to discussion. I dont see any "silver bullet" solution found here, so I will not mark any answer as accepted, but will vote up all answers to this question.

提交回复
热议问题