[英]how to connect form values in jsp to controller in spring MVC
我是春季MVC的新手。 我想將模型bean附加到綁定值的形式並將其傳遞給控制器。 所以我做了以下方式
在jsp中
<form:form modelattribute="model">
<form:input path="var1"/>
</form:form>
在控制器中
pulic void method(@modelattribute("model")Bean bean)
{
//my code
}
但是在訪問表單時,在呈現jsp時將錯誤拋出為異常,名稱模型中不存在這樣的bean
如何解決呢? 幫我
假設您的模型類如下所示:
public class MyModel{
private String propOne;
private String porpTwo;
/*Skipping getters and setters*/
}
to map the user inputs to your form bean: 使用將用戶輸入映射到表單bean:
@RequestParam("/myPage")
public String myController(@ModelAttribute MyModel myModel){
/*Do your processing here*/
}
page, just give your input fields same name (Html attribute: name) as the properties inside the bean to be mapped: 在頁面上,只需為輸入字段提供與要映射的bean內的屬性相同的名稱 (HTML屬性:名稱)即可:
<form:input name="propOne" class="xyz" />
<form:input name="propTwo" class="xyz" />
這樣做可以完成您的bean映射。
您需要在渲染頁面之前保存模型。
uiModel.addAttribute("model", new Bean());
在Spring MVC中,最好在提供模型的控制器中使用@ModelAttribute批注。 在呈現JSP之前,這將被調用並自動添加到模型中。
像這樣
@ModelAttribute
public Model model(){
return new Model();
}
我建議您充分閱讀Spring MVC 文檔
您必須在GET請求期間將表單實例添加到模型中
@RequestMapping(value = "/foo", method = RequestMethod.GET)
public String handler(final Model uiModel)
uiModel.addAttribute("model", new Bean());
//做某事並返回視圖路徑,可能是}
並在處理程序方法中處理POST請求
@RequestMapping(value = "/foo", method = RequestMethod.POST)
public String handler(final Bean form)
// process your form bean here and return a view path, probably
}
可在此處找到文檔: http : //static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html
請看一下Vaibhav方法,我已經對其進行了編輯,現在可以正常使用了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.