Spring MVC Form Handling Example

In this example show how to write a simple web based application which makes use of HTML forms using Spring Web MVC framework. To start with it, let us have working STS IDE in place and follow the following steps to develop a Dynamic Form based Web Application using Spring Web Framework:

Step 1: Create a Dynamic Web Project with a name SpringEmployeeApp and create a package com.dineshonjava.controller under the src folder in the created project.

Step 2: Add below mentioned Spring 3.0 libraries and other libraries into the folder WebRoot/WEB-INF/lib

  • commons-logging-1.1.1.jar
  • org.springframework.asm-3.0.0.jar
  • org.springframework.beans-3.0.0.jar
  • org.springframework.context-3.0.0.jar
  • org.springframework.core-3.0.0.jar
  • org.springframework.expression-3.0.0.jar
  • org.springframework.web.servlet-3.0.0.jar
  • org.springframework.web-3.0.0.jar
  • spring-web.3.0.0.jar
 Step 3: Create a Java class EmployeeController and Employee under the com.dineshonjava.controller com.dineshonjava.bean package respectively.

Step 4: Create Spring configuration files Web.xml and sdnext-servlet.xml under the WebRoot/WEB-INF/ folder.

Step 5: Create a sub-folder with a name views under the WebRoot/WEB-INF folder. Create a view file employeeForm.jsp and employeeDetail.jsp under this sub-folder.

Step 6: The final step is to create the content of all the source and configuration files name sdnext-servlet.xml under the sub-folder WebRoot/WEB-INF/config and export the application as explained below.

Software versions used to run the sample code:

  • Spring 3.0
  • Java 1.6
  • Tomcat 7
  • JSTL 1.2
  • STS Java EE IDE
Web Application Structure:
 Employee.java
package com.dineshonjava.emp.bean;

/**
 * @author Dinesh Rajput
 *
 */
public class Employee {
 private int empId;
 private String name;
 private Long salary;
 private int age;
 /**
  * @return the empId
  */
 public int getEmpId() {
  return empId;
 }
 /**
  * @param empId the empId to set
  */
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 /**
  * @return the name
  */
 public String getName() {
  return name;
 }
 /**
  * @param name the name to set
  */
 public void setName(String name) {
  this.name = name;
 }
 /**
  * @return the salary
  */
 public Long getSalary() {
  return salary;
 }
 /**
  * @param salary the salary to set
  */
 public void setSalary(Long salary) {
  this.salary = salary;
 }
 /**
  * @return the age
  */
 public int getAge() {
  return age;
 }
 /**
  * @param age the age to set
  */
 public void setAge(int age) {
  this.age = age;
 }
 
 public String toString(){
  return "Employee{ name-"+name+" age-"+age+" salary-"+salary+"}";
 }
}
EmployeeController.java
package com.dineshonjava.emp.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;

import com.dineshonjava.emp.bean.Employee;

/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class EmployeeController {
 
  @RequestMapping(value = "/employee", method = RequestMethod.GET)
  public ModelAndView employee() {
    return new ModelAndView("employeeForm", "command", new Employee());
   }
    
  @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
  public String addEmployee(@ModelAttribute("SpringWeb")Employee employee, ModelMap model) {
     model.addAttribute("name", employee.getName());
     model.addAttribute("age", employee.getAge());
     model.addAttribute("empId", employee.getEmpId());
     model.addAttribute("salary", employee.getSalary());
     return "employeeDetail";
   }
}
Here the first service method employee(), we have passed a blank Employee object in the ModelAndView object with name "command" because the spring framework expects an object with name "command" if you are using tags in your JSP file. So when employee() method is called it returns employeeForm.jsp view.

Second service method addEmployee() will be called against a POST method on the sdnext/addEmployee URL. You will prepare your model object based on the submitted information. Finally a "employeeDetail" view will be returned from the service method, which will result in rendering employeeDetail.jsp


Following is the content of Spring Web configuration file web.xml
<web-app id="WebApp_ID" version="3.0" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <display-name>SpringMVCHelloWorld</display-name>
  <welcome-file-list>
  <welcome-file>/</welcome-file>
 </welcome-file-list>
 
    <servlet>
        <servlet-name>sdnext</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>sdnext</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
Following is the content of another Spring Web configuration file sdnext-servlet.xml
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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">

<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven></mvc:annotation-driven>

<context:component-scan base-package="com.dineshonjava.emp.controller">
</context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
 <property name="prefix" value="/WEB-INF/views/"></property>
 <property name="suffix" value=".jsp"></property>
</bean>

</beans>
employeeForm.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"%>

<html>
 <head>
  
  <title>Spring MVC Form Handling</title>
 </head>
 <body>
<h2>
Employee Data Form</h2>
&lt;form:form action="/sdnext/addEmployee" method="POST"&gt;      
<table><tbody>
<tr>        <td><form:label path="empId">Employee :</form:label></td>      <td><form:input path="empId"></form:input></td>    </tr>
<tr>      <td><form:label path="name">EmployeeName:/form:label&gt;</form:label></td>       <td><form:input path="name"></form:input></td>    </tr>
<tr>       <td><form:label path="age">Employee Age:</form:label></td>       <td><form:input path="age"></form:input></td>     </tr>
<tr>      <td><form:label path="salary">Employee Salary:</form:label></td>     <td><form:input path="salary"></form:input></td>    </tr>
<tr>         <td colspan="2">&lt;input type="submit" value="Submit"/&gt;  </td>       </tr>
</tbody></table>
</form:form>
</body>
</html>
employeeDetail.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"%>

<html>
   <head>
 <title>Spring MVC Form Handling</title>
   </head>
<body>
<h2>
Submitted Employee Information</h2>
<table border="1"><tbody>
<tr>     <td>Employee ID </td>      <td>${empId}</td>   </tr>
<tr>      <td>Employee Name</td>      <td>${name}</td>  </tr>
<tr>     <td>Employee Age</td>      <td>${age}</td>     </tr>
<tr>      <td>Employee Salary</td>       <td>${salary}</td> </tr>
</tbody></table>
</body>
</html>

Once you are done with creating source and configuration files, export your application. Right click on your application and use Export-> WAR File option and save your SpringEmplyeeApp.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Now try a URL http://localhost:8080/sdnext/employee and you should see the following result if everything is fine with your Spring Web Application:



After submitting required information click on submit button to submit the form. You should see the following result if everything is fine with your Spring Web Application:

Download SouceCode+Libs
SpringEmployeeApp.zip




18 comments:

  1. @ModelAttribute("SpringWeb")Employee employee

    can any body tell me
    what "Springweb" mean here ??

    ReplyDelete
    Replies
    1. Methods returning objects that are added directly to the model, including the attribute name and value. This attribute name "SpringWeb" is adding to the jsp file where we want display or capture these attribute.
      example-
      ---
      ---


      Thanks,

      Delete
    2. example-
      <form:form action="employee/addEmployee" modelAttribute="SpringWeb">
      ---
      ---
      </form:form>

      Delete
    3. thank you. very much.

      Delete
    4. nice explaination dinesh and can you give example only using mapping configuration file

      Delete
    5. Thanks friends for learning with dineshonjava.com.

      Could please explain more your requirement?

      Regards,
      Dinesh

      Delete
  2. for this example, when I start Apache TOmcat I am getting this errors, CAN YOU PLEASE HELP ME

    INFO: validateJarFile(D:\Softwares\Program softwares\apache-tomcat-7.0.22\webapps\SpringEmployeeApp\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

    java.lang.NoSuchMethodException: org.apache.catalina.deploy.WebXml addServlet

    Parse error in application web.xml file at file://D:\Softwares\Program softwares\apache-tomcat-7.0.22\conf\web.xml
    org.xml.sax.SAXParseException; systemId: file://D/Softwares/Program%20softwares/apache-tomcat-7.0.22/conf/web.xml; lineNumber: 103; columnNumber: 15; Error at (103, 15) : org.apache.catalina.deploy.WebXml addServlet

    ReplyDelete
  3. Hi Dinesh,
    I tried to download and this example bt the hello world is begin downloaded in place of form handling, Please verify that

    ReplyDelete
    Replies
    1. Hi Friends,

      Thanks for to help resolving this problem. Now you can download correct example.

      Thanks,
      Anamika

      Delete
  4. Hi Friends,

    Thanks for to help resolving this problem. Now you can download correct example.

    Thanks,
    Anamika

    ReplyDelete
  5. I have downloaded the code, imported it but it shows the error
    HTTP Status 500 - org.springframework.beans.NotReadablePropertyException: Invalid property 'address' of bean class [com.dineshonjava.emp.bean.Employee]: Bean property 'address' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

    plz help me

    ReplyDelete
    Replies
    1. Hi Laxmi,

      I have fixed this problem so Please download and deploy again.
      Hopefully you are successfully run this application.

      Thanks,
      Anamika

      Delete
  6. In employeeForm.jsp you put:


    It doesn't work for me, I put:


    Now, works.

    ReplyDelete
  7. form:form action="/sdnext/addEmployee" method="POST"
    form:form action="addEmployee" method="POST"

    ReplyDelete
  8. Hi Dinesh, i have downloaded helloworld example and the form handling examples and imported in to eclipse but for both i am getting 404 error like resource is not avaiable.. is der problem i n the downloaded file or my self done mistake please let me know

    ReplyDelete
    Replies
    1. This may due to context root what you are using please update context root of your application.

      Thanks,
      Dinesh

      Delete
  9. Hi
    Can any one expalin me when i Deploy Downloaded FileHandlig Example it is Working Fine, But I am not Understanding
    on the URL It Like On the palce of application name it is taking "sdnext" from where it is taking that.

    If i develop application with same details with dis URL it is Displaying Form ,but if i submit that form it is giving 404 requested resource is not availabe this error it is giving anyone help me.

    ReplyDelete