Joh*_*ohn 5 java spring jsp spring-mvc
当只有一个字符串要传递给控制器时,使用 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?
Run Code Online (Sandbox Code Playgroud)
如果我删除 modelAttribute="key" 标签,我会得到:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for
bean name 'command' available as request attribute
Run Code Online (Sandbox Code Playgroud)
联合应用程序
<form:form method="post" action="myAction" modelAttribute="key">
<td>
<form:input path="key" value="${myValue}"/>
<input type="submit" value="Submit"/>
</td>
</form:form>
Run Code Online (Sandbox Code Playgroud)
控制器
@RequestMapping(value = "/myAction", method = RequestMethod.POST)
public String handleMyActionRequest(@ModelAttribute("key") String key, Model model) {
// do stuff with key string.
return HOME_PAGE_REDIRECT;
}
Run Code Online (Sandbox Code Playgroud)
提交表单时将单个字符串传递给控制器方法而无需创建新类的约定是什么?
我刚刚有了这个想法,但我真的不知道它是否总体上是可取的。毕竟,这只是您想要避免的过程的在线版本。无论如何,我就这样:
在您的支持 bean 中,将字符串添加到模型中,如下所示:
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
Object theTempBean = new Object(){
public String key = "blahblahblah";
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
};
model.addAttribute("theTempBean", theTempBean);
String viewName = "home";
return new ModelAndView(viewName, "command", model);
}
Run Code Online (Sandbox Code Playgroud)
JSP 应该如下所示:
<form:form action="/myAction" modelAttribute="theTempBean">
<form:input path="key" />
<input
type="submit" value="Submit" />
</form:form>
Run Code Online (Sandbox Code Playgroud)
那么,处理表单发布的 Web 控制器的方法应该如下所示:
@RequestMapping(path = "/myAction")
public String myAction(@RequestParam("key") String param){
logger.info(param);
return "home";
}
Run Code Online (Sandbox Code Playgroud)
我测试了这个简单的示例,它在 Spring 版本 4.2.0.RELEASE 和 Jetty Maven 插件版本 9.3.2.v20150730 中按预期工作。
编辑
有一个错误。如果您决定这样做,则必须在任何请求中设置“theTempBean”(也许它可能成为一个@ModelAttribute。同样,它只是一个额外 bean 类的内联版本)。这是固定操作处理程序方法:
@RequestMapping(path = "/myAction")
public String myAction(@RequestParam("key") String param
, Model model){
logger.info(param);
Object theTempBean = new Object(){
public String key = param;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
};
model.addAttribute("theTempBean", theTempBean);
return jspViewName("home");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4029 次 |
| 最近记录: |