Spring表单命令可以是Map吗?
Spring表单命令可以是Map吗? 我通过扩展HashMap并使用['property']
表示法引用属性来使我的命令成为Map,但它不起作用。
命令:
public class MyCommand extends HashMap { }
HTML表单:
Name:
导致错误:
org.springframework.beans.NotReadablePropertyException: Invalid property '[name]' of bean class [com.me.MyCommand]: Bean property '[name]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
这是不允许的还是我的语法不正确?
Springn MVC命令需要使用JavaBeans命名conventins(即getXXX()和setXXX()),所以不能为此使用映射。
一种替代方法是使用具有单个Map属性的bean,即:
public class MyCommand { private final Map properties = new HashMap(); public Map getProperties() { return properties; } // setter optional }
然后你可以做这样的事情(不是100%肯定语法,但它是可能的):
Name:
结合cletus和dbell的答案我实际上可以使它工作,并希望与您分享解决方案(包括提交表单时的值绑定,报告的cletus解决方案的缺陷)
您不能直接使用map作为命令,但是有另一个域对象需要包装一个惰性映射
public class SettingsInformation { private Map settingsMap= MapUtils.lazyMap(new HashMap(),FactoryUtils.instantiateFactory(SettingsValue.class)); public Map getSettingsMap() { return settingsMap; } public void setSettingsMap(Map settingsMap) { this.settingsMap = settingsMap; } }
SettingsValue是一个实际包装值的类。
public class SettingsValue { private String value; public SettingsValue(String value) { this.value = value; } public SettingsValue() { } public String getValue() { return value; } public void setValue(String propertyValue) { this.value = propertyValue; }
提供模型的控制器方法如下所示:
@RequestMapping(value="/settings", method=RequestMethod.GET) public ModelAndView showSettings() { ModelAndView modelAndView = new ModelAndView("settings"); SettingsDTO settingsDTO = settingsService.getSettings(); Map settings = settingsDTO.getSettings(); SettingsInformation settingsInformation = new SettingsInformation(); for (Entry settingsEntry : settings.entrySet()) { SettingsValue settingsValue = new SettingsValue(settingsEntry.getValue()); settingsInformation.getSettingsMap().put(settingsEntry.getKey(), settingsValue); } modelAndView.addObject("settings", settingsInformation); return modelAndView; }
您的表单应如下所示
"/>
处理表单提交的控制器方法照常工作
@RequestMapping(value="/settings", method=RequestMethod.POST) public ModelAndView updateSettings(@ModelAttribute(value="settings") SettingsInformation settings) { [...] }
我validation了SettingsInformation bean实际上是用表单中的值填充的。
谢谢你帮我这个; 如果您有任何问题随时问。
好吧,我有一个适合我的解决方案,我使用MapUtils.lazyMap
//我的根域
public class StandardDomain { private Map templateMap= MapUtils.lazyMap(new HashMap(),FactoryUtils.instantiateFactory(AnotherDomainObj.class)); public Map getTemplateContentMap() { return templateMap; } public void setTemplateContentMap(Map templateMap) { templateMap = templateMap; } }
//我的第二个域名
public class AnotherDomainObj { String propertyValue=""; public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } }
//在我的JSP中
是的它可以但是……你需要引用它作为
例如