1. Overview
In this article, we will discuss Spring forms and data binding to a controller. Also, we will have a look at one of the main annotations in Spring MVC i.e. @ModelAttribute.
Of course, Spring MVC is a complex topic with lots of things you need to understand to use it to its full potential, so definitely dig deeper into the framework here.
2. The Model
First – let's define a simple entity that we're going to display and bind to the form:
public class Employee {
private String name;
private long id;
private String contactNumber;
// standard getters and setters
}
This will be our form-backing object.
3. The View
Next – let's define the actual form, and of course, the HTML file that contains it. We're going to be using a page where a new employee is created/registered:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
</head>
<body>
<h3>Welcome, Enter The Employee Details</h3>
<form:form method="POST"
action="/spring-mvc-xml/addEmployee" modelAttribute="employee">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id"/></td>
</tr>
<tr>
<td><form:label path="contactNumber">
Contact Number</form:label></td>
<td><form:input path="contactNumber"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
First – notice that we're including a tag library into our JSP page – the form taglib – to help with defining our form.
Next – the form:form tag plays an important role here; it’s very similar to the regular HTLM