In this post we will see an example for Spring MVC input tag.
Input tag is used to create a text box in the Form and get data from user.
Syntax
1 |
<form:input path="firstName" /> |
This gets converted to HTML and looks like
1 |
<input id="firstName" name="firstName" type="text" value=""> |
Lets see an example on how to use the Spring MVC input tag in a form, get data from User and submit it back to Controller and then display again on the UI.
Spring MVC Input tag Example
1. Model – Employee.java
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.kscodes.sampleproject.model; public class Employee { private String firstName; private String lastName; private String department; // getters and Setters .... } |
2. Controller – EmployeeController.java
Controller displays the form to user that contains the Input Tag. When the user fills the form and clicks submit, the data is submitted to the Controller which sends data to the View to display
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.kscodes.sampleproject.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.kscodes.sampleproject.model.Employee; @Controller public class EmployeeController { @RequestMapping(value = "/employee", method = RequestMethod.GET) public ModelAndView showEmployeeForm() { Employee employee = new Employee(); // Add the command object to the modelview ModelAndView mv = new ModelAndView("employee"); mv.addObject("employee", employee); return mv; } @RequestMapping(value = "/employee", method = RequestMethod.POST) public String submitForm(Model model, Employee employee, BindingResult result) { model.addAttribute("employee", employee); return "success"; } } |
3. View- employee.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Spring MVC - Employee</title> </head> <body> <h2>Employee Details</h2> <form:form method="post" commandName="employee"> <table> <tr> <td><form:label path="firstName">First Name :</form:label></td> <td><form:input path="firstName" /></td> </tr> <tr> <td><form:label path="lastName">Last Name :</form:label></td> <td><form:input path="lastName" /></td> </tr> <tr> <td><form:label path="department">Department :</form:label></td> <td><form:input path="department" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit" /></td> </tr> </table> </form:form> </body> </html> |