【发布时间】:2015-11-17 02:29:44
【问题描述】:
当只有一个字符串要传递给控制器时,使用 modelAttribute="" 标记和 path="" 标记对我没有意义。然而,当一个表单有多个文本框时,为它们创建一个对象模型实际上是有意义的。这样modelAttribute标签代表对象,即“Employee”,而path标签代表字段,即“firstName”、“lastName”、“salary”。
当你只想传递一个字符串时你会怎么做?我不应该用 getKey() 和 setKey() 或任何疯狂的“key”字段创建一个“Key”类,只是为了将字符串传递给控制器方法,对吧?这种情况下的约定是什么?
如果我只是在页面加载时执行model.addAttribute("key", ""),我会得到:
org.springframework.beans.NotReadablePropertyException: Invalid property 'key'
of bean class [java.lang.String]: Bean property 'key' is not readable or has an invalid
getter method: Does the return type of the getter match the parameter type of the setter?
如果我删除 modelAttribute="key" 标签,我会得到:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for
bean name 'command' available as request attribute
JSP
<form:form method="post" action="myAction" modelAttribute="key">
<td>
<form:input path="key" value="${myValue}"/>
<input type="submit" value="Submit"/>
</td>
</form:form>
控制器
@RequestMapping(value = "/myAction", method = RequestMethod.POST)
public String handleMyActionRequest(@ModelAttribute("key") String key, Model model) {
// do stuff with key string.
return HOME_PAGE_REDIRECT;
}
在提交表单时将单个字符串传递给控制器方法的约定是什么,而不必创建新类?
【问题讨论】:
标签: java spring jsp spring-mvc