Spring MVC form tags


Lets understand about different form tags of spring through example


Diff_spring_Html_Tags

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

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>Spring</groupId>
  5.   <artifactId>SpringMVCFormTags</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringMVCFormTags Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>javax.servlet</groupId>
  33.             <artifactId>servlet-api</artifactId>
  34.             <version>2.5</version>
  35.             <scope>provided</scope>
  36.         </dependency>
  37.         <dependency>
  38.     <groupId>javax.servlet.jsp.jstl</groupId>
  39.     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
  40.     <version>1.2.1</version>
  41. </dependency>
  42. <dependency>
  43.     <groupId>taglibs</groupId>
  44.     <artifactId>standard</artifactId>
  45.     <version>1.1.2</version>
  46. </dependency>
  47.  
  48.   </dependencies>
  49.   <build>
  50.     <finalName>SpringMVCFormTags</finalName>
  51.     <plugins>
  52.             <plugin>
  53.                 <groupId>org.apache.maven.plugins</groupId>
  54.                 <artifactId>maven-compiler-plugin</artifactId>
  55.                 <version>2.5.1</version>
  56.                 <configuration>
  57.                     <source>1.8</source>
  58.                     <target>1.8</target>
  59.                 </configuration>
  60.             </plugin>
  61.         </plugins>
  62.   </build>
  63. </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

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Spring MVC Form Tags</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.         </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27.  
  28.     <!-- Loads Spring Security configuration file -->
  29.      <context-param>
  30.         <param-name>contextConfigLocation</param-name>
  31.         <param-value>
  32.             /WEB-INF/spring-mvc.xml,
  33.         </param-value>
  34.     </context-param>
  35. </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)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.      
  16.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  17.         <property name="prefix" value="/WEB-INF/pages/" />
  18.         <property name="suffix" value=".jsp" />
  19.     </bean>
  20. </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

  1. package com.kb.model;
  2.  
  3. import java.util.List;
  4.  
  5. public class User {
  6.  
  7.     private String name;
  8.    
  9.     private String email;
  10.    
  11.     private String gender;
  12.    
  13.     private String password;
  14.    
  15.     private String passwordConfirm;
  16.    
  17.     private List<String> courses;
  18.  
  19.     private List<String> batches;
  20.    
  21.     private String hiddenMsg;
  22.  
  23.     public String getName() {
  24.         return name;
  25.     }
  26.  
  27.     public void setName(String name) {
  28.         this.name = name;
  29.     }
  30.  
  31.     public String getEmail() {
  32.         return email;
  33.     }
  34.  
  35.     public void setEmail(String email) {
  36.         this.email = email;
  37.     }
  38.  
  39.     public String getGender() {
  40.         return gender;
  41.     }
  42.  
  43.     public void setGender(String gender) {
  44.         this.gender = gender;
  45.     }
  46.  
  47.     public String getPassword() {
  48.         return password;
  49.     }
  50.  
  51.     public void setPassword(String password) {
  52.         this.password = password;
  53.     }
  54.  
  55.     public String getPasswordConfirm() {
  56.         return passwordConfirm;
  57.     }
  58.  
  59.     public void setPasswordConfirm(String passwordConfirm) {
  60.         this.passwordConfirm = passwordConfirm;
  61.     }
  62.  
  63.     public List<String> getCourses() {
  64.         return courses;
  65.     }
  66.  
  67.     public void setCourses(List<String> courses) {
  68.         this.courses = courses;
  69.     }
  70.  
  71.     public List<String> getBatches() {
  72.         return batches;
  73.     }
  74.  
  75.     public void setBatches(List<String> batches) {
  76.         this.batches = batches;
  77.     }
  78.  
  79.     public String getHiddenMsg() {
  80.         return hiddenMsg;
  81.     }
  82.  
  83.     public void setHiddenMsg(String hiddenMsg) {
  84.         this.hiddenMsg = hiddenMsg;
  85.     }
  86. }
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

  1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  2. <html>
  3. <head>
  4. <title>Spring MVC form tags</title>
  5. </head>
  6.  
  7. <body>
  8.     <h2>Fill below form to register</h2>
  9.  
  10.     <form:form method="POST" modelAttribute="user" action="register">
  11.         <table>
  12.             <tr>
  13.                 <td>Enter your name:</td>
  14.                 <td><form:input path="name" /></td>
  15.                 <td><form:errors path="name" cssStyle="color: #ff0000;"/></td>
  16.             </tr>
  17.             <tr>
  18.                 <td>Enter your mail:</td>
  19.                 <td><form:input path="email" /></td>
  20.                 <td><form:errors path="email" cssStyle="color: #ff0000;" /></td>
  21.             </tr>
  22.             <tr>
  23.                 <td>Enter your gender</td>
  24.                 <td><form:radiobuttons path="gender" items="${genders}" /></td>
  25.                 <td><form:errors path="gender" cssStyle="color: #ff0000;"/></td>
  26.             </tr>
  27.             <tr>
  28.                 <td>Enter a password:</td>
  29.                 <td><form:password path="password"  showPassword="true"/></td>
  30.                 <td><form:errors path="password" cssStyle="color: #ff0000;"/></td>
  31.             <tr>
  32.                 <td>Confirm your password:</td>
  33.                 <td><form:password path="passwordConfirm" showPassword="true"/></td>
  34.                 <td><form:errors path="passwordConfirm" cssStyle="color: #ff0000;"/></td>
  35.             </tr>
  36.            
  37.             <tr>
  38.                 <td>Choose your Batches:</td>
  39.                 <td><form:checkboxes path="batches" items="${batches}" /></td>
  40.                 <td><form:errors path="batches" cssStyle="color: #ff0000;"/></td>
  41.             </tr>
  42.            
  43.             <tr>
  44.                 <td>Please select your courses:</td>
  45.                 <td><form:select path="courses">
  46.                       <form:option value="" label="Please Select" />
  47.                       <form:options items="${courses}" />
  48.                        </form:select>
  49.                 </td>
  50.                 <td><form:errors path="courses" cssStyle="color: #ff0000;" /></td>
  51.             </tr>
  52.            
  53.             <tr>               
  54.                 <form:hidden path="hiddenMsg"/>
  55.             </tr>
  56.             <tr>
  57.                 <td><input type="submit" name="submit" value="Register"></td>
  58.             </tr>
  59.             <tr>
  60.         </table>
  61.     </form:form>
  62.  
  63. </body>
  64. </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

  1. package com.kb.controllers;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.ModelAttribute;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11.  
  12. import com.kb.model.User;
  13.  
  14. @Controller
  15. public class RegistrationController {
  16.  
  17.     @RequestMapping(value="/displayRegistrationPage",method=RequestMethod.GET)
  18.     public String displayUserPage(Model model){
  19.         User user = new User();
  20.         user.setHiddenMsg("javainsimpleway");
  21.         model.addAttribute("user", user);
  22.         initializeFormValues(model);
  23.         return "/registration";
  24.     }
  25.    
  26.  
  27.     @RequestMapping(value="/register",method=RequestMethod.POST)
  28.     public String displayUserDetails(@ModelAttribute User user,Model model){
  29.         model.addAttribute("user", user);
  30.         return "/success";
  31.     }
  32.    
  33.     private void initializeFormValues(Model model) {
  34.         List<String> courses = new ArrayList<String>();
  35.         courses.add("Java");
  36.         courses.add("J2EE");
  37.         courses.add("Spring");
  38.         courses.add("Hibernate");
  39.         courses.add("Jquery");
  40.         model.addAttribute("courses", courses);
  41.        
  42.         List<String> genders = new ArrayList<String>();
  43.         genders.add("Male");
  44.         genders.add("Female");
  45.         model.addAttribute("genders", genders);
  46.        
  47.         List<String> batches = new ArrayList<String>();
  48.         batches.add("morning");
  49.         batches.add("evening");
  50.         model.addAttribute("batches", batches);
  51.        
  52.     }
  53. }
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

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8. <title>Insert title here</title>
  9. </head>
  10. <body>
  11. Hey ${user.name} , you are successfully registered.
  12. <br>
  13. You have chosen the  below courses:
  14. <br>
  15.     <c:forEach var="course" items="${user.courses}">  
  16.             <c:out value="${course}"/><br>
  17.     </c:forEach>
  18. <br>
  19. You have chosen the  below batches:
  20. <br>
  21.     <c:forEach var="batch" items="${user.batches}">  
  22.             <c:out value="${batch}"/><br>
  23.     </c:forEach>
  24. <br>
  25. Your hidden name is ${user.hiddenMsg}
  26. </body>
  27. </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

Download this project SpringMVCFormTags.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on