In this following example, we will learn how to write a simple web based application which makes use of HTML forms using Spring Web MVC framework. Create a Dynamic Web Application in Eclipse to develop a Dynamic Form based Web Application using Spring Web Framework. In this example, the user fills in a web form and click Submit button. The server receives the request from the user, processes the input and finally returns a response back to the user. Let’s go ahead and see how the Spring MVC framework supports form handling.
Folder Structure :
- Create a Dynamic Web Project RegistrationForm and create a package for our src files “com.javainterviewpoint“
- Place the Spring 3 jar files under WEB-INF/Lib
- Put the index.jsp under the WebContent directory.
- Create the Java classes MVC_Controller.java and RegistrationBean.java under com.javainterviewpoint folder.
- Place the SpringConfig-servlet.xml and web.xml under the WEB-INF directory
- View files RegistrationForm.jsp and RegistrationSuccess.jsp are put under the sub directory under WEB-INF/Jsp
Index.jsp
This is simply a startup page which redirects the user to our RegistrationForm.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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> <a href="displayForm.html">Click here to Register</a> </body> </html>
RegistrationForm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <!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> <form:form action="Register" method="POST" commandName="rb"> <table> <tr> <td>Name</td> <td><form:input path="name"/></td> </tr> <tr> <td>Age</td> <td><form:input path="age"/></td> </tr> <tr> <td>Profession</td> <td><form:select path="profession" items="${professionList}"></form:select></td> </tr> <tr> <td><input type="submit" value="Register"/></td><td></td> </tr> </table> </form:form> </body> </html>
When the user clicks on the link “Click here to Register” the controller will redirect the user to our RegistrationFrom.
Here <form:form> plays vital role, which is similar to that of the HTML <form> tag, you could see a special attribute called commandName=”rb”, where rb act as the form-backing object.
All the form tags <form:input>,<form:select> has a particular attribute called path, this specifies the name of a property of the model class (RegistrationBean.java)
MVC_Controller.java
package com.javainterviewpoint; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class MVC_Controller { @ModelAttribute("professionList") public List populateProfession() { List professionList = new ArrayList(); professionList.add("Developer"); professionList.add("Manager"); professionList.add("Architect"); return professionList; } @RequestMapping("/displayForm") public ModelAndView Welcome() { return new ModelAndView("RegistrationForm","rb",new RegistrationBean()); } @RequestMapping(value="/Register",method=RequestMethod.POST) public String processRegistration(@ModelAttribute("rb")RegistrationBean rb) { System.out.println(rb.getName()); return "RegistrationSuccess"; } }
We can see the Controller (@Controller annotated) is designed to handle two different requests “displayForm” and “Register” under that we implement two methods “Welcome()” and “processRegistration()” let’s see each of the methods in the controller class in detail.
- Welcome():
This method does nothing but simply redirecting to the RegistrationForm.jsp returns the ModelAndView object which has three parameters
return new ModelAndView("RegistrationForm","rb",new RegistrationBean());
1. View component to be redirected to, here the RegistrationForm.jsp is the view component.
2. key for the form-backing object.
3. Value for the key.
- processRegistration():
This method handles POST request when the form gets submitted. The key parameter here is
@ModelAttribute("rb")RegistrationBean rb
The @ModelAttribute annotation binds the key “rb” and makes it available to the body again, the key must match the commandName in <form:form> tag of the RegistrationForm.jsp.
When the Form is submitted Spring will automatically map the values to the backing object and hence we can access the values directly like below
System.out.println(rb.getName());
Finally, upon processing, the controller returns the Success view page “RegistrationSuccess”.
One more important thing to be noted in the controller is @ModelAttribute(“professionList”), In the RegistrationForm.jsp we are dynamically populating the “profession” select box, the populateProfession() only returns the values on the screen when ${professionList} is hit.
RegistrationBean.java
package com.javainterviewpoint; public class RegistrationBean { String name; int age; String profession; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getProfession() { return profession; } public void setProfession(String profession) { this.profession = profession; } }
Our model has three fields such as the name, age, profession which binds to the corresponding fields in the view component (RegistrationForm.jsp) and hence it is called as form-backing object.
RegistrationSuccess.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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> <h1>Registration Successful!!</h1> <table border="1"> <tr> <td>Name</td> <td>${rb.name}</td> </tr> <tr> <td>Age</td> <td>${rb.age}</td> </tr> <tr> <td>Profession</td> <td>${rb.profession}</td> </tr> </table> </body> </html>
This simply uses the JSP Expression Language to display the values of the model “rb”.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>SpringConfig</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringConfig</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Spring Configuration File
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.jackson"></context:component-scan> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/Jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
Testing our Application
Once the application is deployed on to the server, run with below URL
http://localhost:9090/SpringMVCForms/
Go ahead and click the hyperlink to get our form.
Click on the Register button, we will get the success page as below.
Hurray!! We have built our first Spring MVC based Registration Form
Arun Sundaramoorthy says
Very nice explanation.
harshavardhan says
you didn’t mention what to write in SpringConfig-servlet.xml and web.xml files
javainterviewpoint says
Added the configuration files
Ashish Sanu says
for anyone referring this page note that commandName in jsp is deprecated better use ModelAttribute