我们需要使用以下JSP标签将实体数据绑定到JSP表单字段:
该表单来自Spring标签库:
以下不是完整的HTML代码,但我希望您能够理解:
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<form:form action="save" method="post" modelAttribute="patient">
<table>
<tr>
<td>Name</td>
<td>
<form:input path="patient.patient_name" /> <br />
</td>
</tr>
<tr>
<td>Phone</td>
<td>
<form:input path="patient.phone_number" /> <br />
</td>
</tr>
<tr>
<td colspan="2"><button type="submit">Submit</button></td>
</tr>
</table>
</form:form>
表单需要处理两次,一次是在呈现表单之前,我们需要为属性值modelAttribute="patient"
提供适当的bean实例化。
- 为此,控制器类(在类定义级别)需要有
@RequestMapping
注释。
- 您需要按以下方式设置处理程序方法参数
@GetMapping("logincreate")
public String handleLoginCreate(@ModelAttribute("login") Login login, Model model)
{
System.out.println(" Inside handleLoginCreate ");
model.addAttribute("login",login);
return "logincreate";
}
Spring将扫描所有处理程序方法@ModelAttribute
,并使用Login类的默认构造函数对其进行实例化,并调用其所有getter和setter(用于在表单与“login”之间进行jsp绑定)。如果缺少以下任何一个,则不会显示jsp,会抛出各种异常
- getters/setters
- 默认构造函数
- model.addAttribute("login",login);
- 类级别的@RequestMapping
- 方法参数级别的@ModelAttribute
此外,在jsp中的操作处理程序方法,在上述形式中 action="save"
,处理程序方法可能如下所示:
@PostMapping("save")
public String saveLoginDetails(@ModelAttribute("login") Login login, Model model) {
System.out.println(" Inside save login details ");
System.out.println("The login object is " + login.toString());
System.out.println("The model object contains the login attribute"+ model.getAttribute("login"));
loginService.saveLogin(login);
return "welcome";
}
重要的学习内容是:
- 在表单启动之前,Spring 应该有适当的注释来指示表单的支持 bean,在上面的例子中,“支持 bean” 或 “绑定对象” 是具有适当处理程序方法参数注释
@ModelAttribute("login") Login login
的登录。