[英]Spring JSP: Trouble with spring form with modelAttribute=“” and path=“”
當只有一個字符串要傳遞給控制器時,使用modelAttribute =“”標簽和path =“”標簽對我沒有意義。 但是,當表單有多個文本框時,實際上有一個對象模型是有意義的。 這樣,modelAttribute標記表示對象,即“Employee”,路徑標記表示字段,即“firstName”,“lastName”,“salary”。
當你只想傳遞一個字符串時,你會怎么做? 我不應該創建一個帶有“key”字段的“Key”類,其中包含getKey()和setKey()或任何一種瘋狂只是為了將字符串傳遞給控制器方法,對吧? 在這種情況下的慣例是什么?
如果我只是在頁面加載時執行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;
}
在提交表單時將單個字符串傳遞給控制器方法的慣例是什么,而不必創建新類?
我剛才有了這個想法,但我真的不知道它是否一般都是可取的。 畢竟,它只是您想要避免的流程的在線版本。 無論如何,我去了:
在您的支持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);
}
JSP應該如下所示:
<form:form action="/myAction" modelAttribute="theTempBean">
<form:input path="key" />
<input
type="submit" value="Submit" />
</form:form>
然后,處理表單帖子的Web控制器的方法應該類似於以下內容:
@RequestMapping(path = "/myAction")
public String myAction(@RequestParam("key") String param){
logger.info(param);
return "home";
}
我測試了這個簡單的例子,它與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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.