Spring MVC Form Handling Example

The following 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 Eclipse IDE in place and follow the following steps to develope a Dynamic Form based Web Application using Spring Web Framework:

Step

Description

1

Create a Dynamic Web Project with a name HelloWeb and create a package com.tutorialspoint under the src folder in the created project.

2

Drag and drop below mentioned Spring and other libraries into the folder WebContent/WEB-INF/lib.

3

Create a Java classes Student and StudentController under the com.tutorialspoint package.

Here the first service method student(), we have passed a blank Student object in the ModelAndView object with name "command" because the spring framework expects an object with name "command" if you are using <form:form> tags in your JSP file. So when student() method is called it returns student.jsp view.

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

Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEB-INF/lib folder.

commons-logging-x.y.z.jar

org.springframework.asm-x.y.z.jar

org.springframework.beans-x.y.z.jar

org.springframework.context-x.y.z.jar

org.springframework.core-x.y.z.jar

org.springframework.expression-x.y.z.jar

org.springframework.web.servlet-x.y.z.jar

org.springframework.web-x.y.z.jar

spring-web.jar

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 SpringWeb.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/SpringWeb/student 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: