Sometimes it is useful to be able to create a fixed ModelAndView instance in a bean context, with populated model data - after all if there is no code required to populate the model why not just do it in the context config?
For example:
However this is not possible as far as I can tell because ModelAndView protects its Model map, so it would need a ModelAndViewBean approach to act as a factory for the model. This would be very useful for passing complete static ModelAndView instances to controllers.Code:<bean name="view.pleasewait" class="org.springframework.somepackage.ModelAndView"> <property name="viewName" value="pleasewait"/> <property name="model"> <map> <entry key="message"><value>Please wait, updating ...</value></entry> <entry key="refreshURL"><value>/some/completion/page</value></entry> <entry key="delay" value="3"/> </map> </property> </bean>
An alternative, as we only need this currently for a fixed view that is returned by a fixed controller, I implemented a FixedViewController as below:
Code:<bean name="controller.pleasewait" class="yourcorp.pkg.FixedViewController"> <property name="viewName" value="pleasewait"/> <property name="model"> <map> <entry key="message"><value>Please wait, updating ...</value></entry> <entry key="refreshURL"><value>/some/completion/page</value></entry> <entry key="delay" value="3"/> </map> </property> </bean>
It would of course be easy (and nicer) to adapt this so that it uses a ModelAndView as a property, and write a ModelAndViewFactoryBean.Code:package yourcorp.pkg; import org.springframework.web.servlet.mvc.ParameterizableViewController; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; /** * A controller that returns a ModelAndView that can * be set in the configuration to a specific fixed viewName * and a fixed model Map. Property modelName can specify a name for the * model used in the view. * @author mpalmer (marc@anyware.co.uk) */ public class FixedViewController extends ParameterizableViewController { private Map model; private String modelName; public Map getModel() { return model; } public void setModel(Map model) { this.model = model; } public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; } protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { if (modelName == null) { return new ModelAndView( getViewName(), model); } else { return new ModelAndView( getViewName(), modelName, model); } } }
If anybody else thinks this is worthwhile I can lodge it as an RFE in Jira and contribute the code.


Reply With Quote