Spring MVC form tags
Lets understand about different form tags of spring through example
Lets see an example with all the above tags
We will create one Registration form and see how all the tags can be used in real time
Create pom.xml as below
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>Spring</groupId>
- <artifactId>SpringMVCFormTags</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>SpringMVCFormTags Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <properties>
- <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet.jsp.jstl</groupId>
- <artifactId>javax.servlet.jsp.jstl-api</artifactId>
- <version>1.2.1</version>
- </dependency>
- <dependency>
- <groupId>taglibs</groupId>
- <artifactId>standard</artifactId>
- <version>1.1.2</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>SpringMVCFormTags</finalName>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.5.1</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Spring</groupId> <artifactId>SpringMVCFormTags</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMVCFormTags Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <org.springframework.version>4.2.0.RELEASE</org.springframework.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <finalName>SpringMVCFormTags</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
Create web.xml
- <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
- version="3.1">
- <display-name>Spring MVC Form Tags</display-name>
- <!-- Spring MVC dispatcher servlet -->
- <servlet>
- <servlet-name>mvc-dispatcher</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/spring-mvc.xml,
- </param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>mvc-dispatcher</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- Loads Spring Security configuration file -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/spring-mvc.xml,
- </param-value>
- </context-param>
- </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Spring MVC Form Tags</display-name> <!-- Spring MVC dispatcher servlet --> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-mvc.xml, </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Loads Spring Security configuration file --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-mvc.xml, </param-value> </context-param> </web-app>
Create spring configuration xml(spring-mvc.xml)
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
- <context:component-scan base-package="com.kb.*" />
- <mvc:annotation-driven />
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/pages/" />
- <property name="suffix" value=".jsp" />
- </bean>
- </beans>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <context:component-scan base-package="com.kb.*" /> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
Create the User Model class which can bind the form data
- package com.kb.model;
- import java.util.List;
- public class User {
- private String name;
- private String email;
- private String gender;
- private String password;
- private String passwordConfirm;
- private List<String> courses;
- private List<String> batches;
- private String hiddenMsg;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getGender() {
- return gender;
- }
- public void setGender(String gender) {
- this.gender = gender;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getPasswordConfirm() {
- return passwordConfirm;
- }
- public void setPasswordConfirm(String passwordConfirm) {
- this.passwordConfirm = passwordConfirm;
- }
- public List<String> getCourses() {
- return courses;
- }
- public void setCourses(List<String> courses) {
- this.courses = courses;
- }
- public List<String> getBatches() {
- return batches;
- }
- public void setBatches(List<String> batches) {
- this.batches = batches;
- }
- public String getHiddenMsg() {
- return hiddenMsg;
- }
- public void setHiddenMsg(String hiddenMsg) {
- this.hiddenMsg = hiddenMsg;
- }
- }
package com.kb.model; import java.util.List; public class User { private String name; private String email; private String gender; private String password; private String passwordConfirm; private List<String> courses; private List<String> batches; private String hiddenMsg; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPasswordConfirm() { return passwordConfirm; } public void setPasswordConfirm(String passwordConfirm) { this.passwordConfirm = passwordConfirm; } public List<String> getCourses() { return courses; } public void setCourses(List<String> courses) { this.courses = courses; } public List<String> getBatches() { return batches; } public void setBatches(List<String> batches) { this.batches = batches; } public String getHiddenMsg() { return hiddenMsg; } public void setHiddenMsg(String hiddenMsg) { this.hiddenMsg = hiddenMsg; } }
Create the registration.jsp page with all the form tags
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
- <html>
- <head>
- <title>Spring MVC form tags</title>
- </head>
- <body>
- <h2>Fill below form to register</h2>
- <form:form method="POST" modelAttribute="user" action="register">
- <table>
- <tr>
- <td>Enter your name:</td>
- <td><form:input path="name" /></td>
- <td><form:errors path="name" cssStyle="color: #ff0000;"/></td>
- </tr>
- <tr>
- <td>Enter your mail:</td>
- <td><form:input path="email" /></td>
- <td><form:errors path="email" cssStyle="color: #ff0000;" /></td>
- </tr>
- <tr>
- <td>Enter your gender</td>
- <td><form:radiobuttons path="gender" items="${genders}" /></td>
- <td><form:errors path="gender" cssStyle="color: #ff0000;"/></td>
- </tr>
- <tr>
- <td>Enter a password:</td>
- <td><form:password path="password" showPassword="true"/></td>
- <td><form:errors path="password" cssStyle="color: #ff0000;"/></td>
- <tr>
- <td>Confirm your password:</td>
- <td><form:password path="passwordConfirm" showPassword="true"/></td>
- <td><form:errors path="passwordConfirm" cssStyle="color: #ff0000;"/></td>
- </tr>
- <tr>
- <td>Choose your Batches:</td>
- <td><form:checkboxes path="batches" items="${batches}" /></td>
- <td><form:errors path="batches" cssStyle="color: #ff0000;"/></td>
- </tr>
- <tr>
- <td>Please select your courses:</td>
- <td><form:select path="courses">
- <form:option value="" label="Please Select" />
- <form:options items="${courses}" />
- </form:select>
- </td>
- <td><form:errors path="courses" cssStyle="color: #ff0000;" /></td>
- </tr>
- <tr>
- <form:hidden path="hiddenMsg"/>
- </tr>
- <tr>
- <td><input type="submit" name="submit" value="Register"></td>
- </tr>
- <tr>
- </table>
- </form:form>
- </body>
- </html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <html> <head> <title>Spring MVC form tags</title> </head> <body> <h2>Fill below form to register</h2> <form:form method="POST" modelAttribute="user" action="register"> <table> <tr> <td>Enter your name:</td> <td><form:input path="name" /></td> <td><form:errors path="name" cssStyle="color: #ff0000;"/></td> </tr> <tr> <td>Enter your mail:</td> <td><form:input path="email" /></td> <td><form:errors path="email" cssStyle="color: #ff0000;" /></td> </tr> <tr> <td>Enter your gender</td> <td><form:radiobuttons path="gender" items="${genders}" /></td> <td><form:errors path="gender" cssStyle="color: #ff0000;"/></td> </tr> <tr> <td>Enter a password:</td> <td><form:password path="password" showPassword="true"/></td> <td><form:errors path="password" cssStyle="color: #ff0000;"/></td> <tr> <td>Confirm your password:</td> <td><form:password path="passwordConfirm" showPassword="true"/></td> <td><form:errors path="passwordConfirm" cssStyle="color: #ff0000;"/></td> </tr> <tr> <td>Choose your Batches:</td> <td><form:checkboxes path="batches" items="${batches}" /></td> <td><form:errors path="batches" cssStyle="color: #ff0000;"/></td> </tr> <tr> <td>Please select your courses:</td> <td><form:select path="courses"> <form:option value="" label="Please Select" /> <form:options items="${courses}" /> </form:select> </td> <td><form:errors path="courses" cssStyle="color: #ff0000;" /></td> </tr> <tr> <form:hidden path="hiddenMsg"/> </tr> <tr> <td><input type="submit" name="submit" value="Register"></td> </tr> <tr> </table> </form:form> </body> </html>
path is the spring form tag attribute used to bind the form field with the model class.
The path we specify in jsp must match with the variable name in the model class.
< form:errors> tag is used to specify error to be displayed for the corresponding field.
We can specify the list of strings directly using items as we used in < form:checkboxes> and < form:select>
List specified with items is used to display multiple values and path is used to bind the selected value into the model class variable.
Create the RegistrationController.java file
- package com.kb.controllers;
- import java.util.ArrayList;
- import java.util.List;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.ModelAttribute;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import com.kb.model.User;
- @Controller
- public class RegistrationController {
- @RequestMapping(value="/displayRegistrationPage",method=RequestMethod.GET)
- public String displayUserPage(Model model){
- User user = new User();
- user.setHiddenMsg("javainsimpleway");
- model.addAttribute("user", user);
- initializeFormValues(model);
- return "/registration";
- }
- @RequestMapping(value="/register",method=RequestMethod.POST)
- public String displayUserDetails(@ModelAttribute User user,Model model){
- model.addAttribute("user", user);
- return "/success";
- }
- private void initializeFormValues(Model model) {
- List<String> courses = new ArrayList<String>();
- courses.add("Java");
- courses.add("J2EE");
- courses.add("Spring");
- courses.add("Hibernate");
- courses.add("Jquery");
- model.addAttribute("courses", courses);
- List<String> genders = new ArrayList<String>();
- genders.add("Male");
- genders.add("Female");
- model.addAttribute("genders", genders);
- List<String> batches = new ArrayList<String>();
- batches.add("morning");
- batches.add("evening");
- model.addAttribute("batches", batches);
- }
- }
package com.kb.controllers; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.kb.model.User; @Controller public class RegistrationController { @RequestMapping(value="/displayRegistrationPage",method=RequestMethod.GET) public String displayUserPage(Model model){ User user = new User(); user.setHiddenMsg("javainsimpleway"); model.addAttribute("user", user); initializeFormValues(model); return "/registration"; } @RequestMapping(value="/register",method=RequestMethod.POST) public String displayUserDetails(@ModelAttribute User user,Model model){ model.addAttribute("user", user); return "/success"; } private void initializeFormValues(Model model) { List<String> courses = new ArrayList<String>(); courses.add("Java"); courses.add("J2EE"); courses.add("Spring"); courses.add("Hibernate"); courses.add("Jquery"); model.addAttribute("courses", courses); List<String> genders = new ArrayList<String>(); genders.add("Male"); genders.add("Female"); model.addAttribute("genders", genders); List<String> batches = new ArrayList<String>(); batches.add("morning"); batches.add("evening"); model.addAttribute("batches", batches); } }
In the controller we have added method to display the Registration page and success page on submit.
We have also written a method to initialize the form with all the required values.
Create the success.jsp page
- <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>Insert title here</title>
- </head>
- <body>
- Hey ${user.name} , you are successfully registered.
- <br>
- You have chosen the below courses:
- <br>
- <c:forEach var="course" items="${user.courses}">
- <c:out value="${course}"/><br>
- </c:forEach>
- <br>
- You have chosen the below batches:
- <br>
- <c:forEach var="batch" items="${user.batches}">
- <c:out value="${batch}"/><br>
- </c:forEach>
- <br>
- Your hidden name is ${user.hiddenMsg}
- </body>
- </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> Hey ${user.name} , you are successfully registered. <br> You have chosen the below courses: <br> <c:forEach var="course" items="${user.courses}"> <c:out value="${course}"/><br> </c:forEach> <br> You have chosen the below batches: <br> <c:forEach var="batch" items="${user.batches}"> <c:out value="${batch}"/><br> </c:forEach> <br> Your hidden name is ${user.hiddenMsg} </body> </html>
Lets build the maven project and copy the war file into server webapps folder.
Run the below url
http://localhost:8080/SpringMVCFormTags/displayRegistrationPage
Fill the form
Click on Register
Hi KB,
Awesome content again!
But a small issue in success.jsp. The tag-lib directive needs to be corrected as .
Thanks Bharat