Wednesday 5 December 2012

Spring MVC Form Handling

Posted by Naveen Katiyar On 21:11 No comments

Form Processing in Spring MVC 3 with Annotation

 In previous article we created a Hello World application in Spring MVC. We learned how to configure Spring MVC in web.xml and how to use different annotations like @Controller, @RequestMapping etc. In this article let us see how to handle forms in Spring 3.0 MVC.

We will use the framework that we created in previous article as a base reference and add up the functionality of form in it.

Our Goal

We are planning to organize a free speak contest in our college and need to create a registration form form providing an interface to the students for participating to the event.

We have to follow bellow steps to successfully implement our requirement :

        • First of all we have to a domain object or pojo class (User.java) for holding form values provided by the user.

        • Then, we will configure our spring configuration file (app-config.xml) to adopt annotation driven configuration for spring mvc.

        • After that we will implement our controller class (RegistrationController.java) that will handle two types of request. One for showing the form to the user and another for processing the input data of form.

        • Then, we will create the form jsp page (registration.jsp) using spring mvc ui taglibs and a registration success page (success.jsp) for the form to confirm the input data in form.

        • After that we will see how to change the error message for data conversion in message resource file (messages.properties).

Getting Started

Let us add the contact form to our Spring 3 MVC Hello World application. Open the index.jsp file and change it to following:

File: WebContent/index.jsp

<jsp:forward page="/registration.htm"></jsp:forward>

The above code will just redirect the user to registration.jsp page.

The View-registration.jsp

Create a JSP file that will display registration form to our users.

 

File: /WebContent/WEB-INF/jsp/registration.jsp

<%@ page session="true" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Hello World with Spring 3 MVC</title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
    </head>
    <body>
        <h1>Registration Form</h1><br />
        <form:form commandName="USER">
        <table>
            <tr><td colspan="2"><form:errors path="*" cssStyle="color : red;"/></td></tr>
            <tr><td>Name : </td><td><form:input path="name" /></td></tr>
            <tr><td>Standard : </td><td><form:input path="standard" /></td></tr>
            <tr><td>Age : </td><td><form:input path="age" /></td></tr>
            <tr><td>Sex : </td><td><form:select path="sex">
                    <form:option value="Male"/>
                    <form:option value="Female"/>
            </form:select></td></tr>
            <tr><td colspan="2"><input type="submit" value="Save Changes" /></td></tr>
        </table>
        </form:form>
    </body>
</html>

registration.jsp will show, how spring mvc form tag will be used to show the form elements in jsp and how errors are shown to the user if any occur.

Spring provided ui taglibs for form elements. <form:errors/> element shows form input errors and any other error associated with the form data. As an example, there is a field “age” in our form which should be an integer and if a user specify any character in the field then conversion will come and that error will be shown in the form.

messages.properties

We will use this file to override conversion error text for the field “age” and will show a user friendly error message. Here is the error message :

typeMismatch.age= Age Field does not contain invalid age. Please enter a number.

 




Spring Configuration File

Create a file spring-servlet.xml in WEB-INF folder and copy following content into it.

File: WEB-INF/spring-servlet.xml
<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" />

 <mvc:annotation-driven />
 <!-- Application Message Bundle -->

	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

		<property name="basename" value="/WEB-INF/messages" />

		<property name="cacheSeconds" value="3000" />

	</bean>

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

 </bean>

 
</beans>

You can learn about <context:component-scan/> and <mvc:annotation-driven/> from previous post. One new thing you can see in this tutorial is “messageSource” bean class org.springframework.context.support.ReloadableResourceBundleMessageSource of spring mvc jar. This class provides message resources to the view. This class takes two parameters :

        1. basename : This parameter should specify the location of the message resource file.

        2. cacheSeconds : This parameter will specify, how much time should be taken by the ReloadableResourceBundleMessageSource class before reloading the messages.

Adding Controller in Spring 3 Form

 

RegistrationController.java

 

Our controller class will handle two requests, one for showing the registration form and another is to handle the submitted form. So there will be two functions with the same request mapping url but the request type will be different. For showing the registration form the request type will be GET and for processing form data submission the request type will be POST. See the bellow code to understand how to specify request type and process form :

package com.naveen.controllers;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import com.naveen.domain.User;

@Controller

@RequestMapping(value="/registration.htm")

public class RegistrationController {

@RequestMapping(method=RequestMethod.GET)

public String showForm(ModelMap model){

User user = new User();

model.addAttribute("USER", user);

return "registration";

}

@RequestMapping(method=RequestMethod.POST)

public String processForm(@ModelAttribute(value="USER") User user,BindingResult result){

if(result.hasErrors()){

return "registration";

}else{

System.out.println("User values is : " + user);

return "success";

}

}

}

As, you can see the class is annotated with @RequestMapping(value=”/registration.htm”), It means all the methods in this class will handle the request for the url “/registration.htm”. showForm will handle the GET request type and will show the registration form. showForm also adds a new instance to the model map so that the new instance can be associated with the shown form. processForm method processes the form data. Here two new things you will learn :

        • @ModelAttribute(value=”USER”) : ModelAttribute annotation will tell spring mvc framework that the “USER” model instance should be assigned as an instance of User class and should be pass to the method processForm.

        • BindingResult result : Spring will find our if any error occur during the creation of User class instance from model instance “USER” and if any error came its description will be pass the method as BindingResult instance.

If there is any error present than it will show again the registration form and if there is no error then success page will be shown to the user.

That’s All Folks

The form is completed now. Just run the application in eclipse by pression Alt + Shift + X, R. It will show the registration form. Just enter view values and press Add button. Once you press the button, it will print the firstname and lastname in sysout logs.

Download Source Code

Click here to download source code

0 comments: