:::: MENU ::::
Browsing posts in: spring mvc

How to create a Spring MVC Form!

Hi All.

Now I am going to show you how you might create a simple Spring MVC form using Eclipse IDE.

The steps to do it, are the next ones:

  1. Create a Dynamic Web Application.
  2. Create the code.
  3. Add the required spring libraries.
  4. Create the web pages to type the information.
  5. Create the x-servlet.xml (configuration of the dispatcher).
  6. Add an index.jsp

Let’s start.

This is the project Structure.

package net.devmanuals.controllers;

import java.util.Map;
import javax.validation.Valid;
import net.devmanuals.form.ValidationForm;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/validationform.html")
public class ValidationController {

// Display the form on the get request
@RequestMapping(method = RequestMethod.GET)
public String showValidatinForm(Map<String, ValidationForm> model) {
ValidationForm validationForm = new ValidationForm();
model.put("validationForm", validationForm);
return "validationform";
}

// Process the form.
@RequestMapping(method = RequestMethod.POST)
public String processValidatinForm(@Valid ValidationForm validationForm,
BindingResult result, Map<String, ValidationForm> model) {
if (result.hasErrors()) {
return "validationform";
}
// Add the saved validationForm to the model
model.put("validationForm", validationForm);
return "validationsuccess";
}

}

**********************************
package net.devmanuals.form;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;

public class ValidationForm {

    @NotEmpty
    @Size(min = 1, max = 20)
    private String userName;

    @NotNull
    @NumberFormat(style = Style.NUMBER)
    @Min(1)
    @Max(110)
    private Integer age;

    @NotEmpty(message = "Password must not be blank.")
    @Size(min = 1, max = 10, message = "Password must between 1 to 10 Characters.")
    private String password;

    @NotEmpty(message = "your comment is empty")
    // @Min(value=10, message="minimo escribe 10 caracteres")
    // @Max(value=20, message="maximo escribe 20 caracteres")
    @Size(min = 10, max = 20, message = "Just Enter 10-20 values")
    private String comments;

    boolean newsletter = true;

    @NotEmpty(message = "your sex is empty")
    private String sex;

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getComments() {
        return comments;
    }

    public boolean isNewsletter() {
        return newsletter;
    }

    public void setNewsletter(boolean newsletter) {
        this.newsletter = newsletter;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getSex() {
        return sex;
    }

}

Now we must to create the jsp pages...

Here you have the source code.
************************
validationForm.jsp
************************
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/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 method="post" action="validationform.html"
        commandName="validationForm">
        <table>
            <tr>
                <td>User Name:<font color="red"><form:errors
                            path="userName" /> </font>
                </td>

                <td><form:input path="userName" />
                </td>
            </tr>
            <tr>
                <td>Age:<font color="red"><form:errors path="age" /> </font>
                </td>

                <td><form:input path="age" />
                </td>
            </tr>
            <tr>
                <td>Password:<font color="red"><form:errors
                            path="password" /> </font>
                </td>

                <td><form:password path="password" />
                </td>
            </tr>
            <tr>
                <td>Comments:<font color="red"><form:errors
                            path="comments" /> </font>
                </td>

                <td><form:textarea path="comments" rows="3" cols="20" />
                </td>
            </tr>
            <tr>
                <td>Suscribe to NewsLetter:<font color="red"><form:errors
                            path="newsletter" /> </font>
                </td>
                <td><form:checkbox path="newsletter" />
                </td>
            </tr>
            <tr>
                <td>Sex :</td>
                <td><form:radiobutton path="sex" value="M" />Male <form:radiobutton
                        path="sex" value="F" />Female</td>
                <td><font color="red"><form:errors path="sex" />
                </font>
                </td>
            </tr>

            <tr>
                <td><input type="submit" value="Enviar" />
                </td>
            </tr>
        </table>
    </form:form>
</body>
</html>
************************
validationSucess.jsp
************************
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="core" 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>
    <font color="red"> Welcome <core:out
            value="${validationForm.userName}" /> <br> </font>
    <h3>Login form successfully validate the form values provided by
        you</h3>
    <p>
        <i>The values provided by you are :</i>
    </p>
    <p>
        <b>UserName :</b>
        <core:out value="${validationForm.userName}" />
    </p>
    <p>
        <b>Age :</b>
        <core:out value="${validationForm.age}" />
    </p>
    <p>
        <b>password :</b>
        <core:out value="${validationForm.password}" />
    </p>

    <p>
        <b>comments:</b>
        <core:out value="${validationForm.comments}" />
    </p>

    <p>
        <b>Suscribe to newsletter?:</b>
        <core:out value="${validationForm.newsletter}" />
    </p>

    <p>
        <b>Sex:</b>
        <core:out value="${validationForm.sex}" />
    </p>

</body>

</html>

-----------------------
dispatcher-servlet.xml
-----------------------
<?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.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 />
    <context:component-scan base-package="net.devmanuals.controllers" />

    <bean id="viewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

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

</beans>

***********************************
messages.properties
***********************************
NotEmpty.validationForm.userName=User Name must not be blank.
Size.validationForm.userName=User Name must between 1 to 20 characters

NotEmpty.validationForm.comments=mensaje de comentario vacio
Size.validationForm.comments=mensaje de tamanio no valido en el comentario

----------------------------
web.xml
----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
    <display-name>Spring3LoginValidation</display-name>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/forms/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

++++++++++++++++++++++++++++++++++
And the last one is the index.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>Spring 3 Login Validation</title>
</head>
<body>
    <h1>Spring 3 Login Validation</h1>
    <ul>
        <li><a href="forms/validationform.html">Validation Form</a>
        </li>
    </ul>
</body>
</html>