Alex
Alex

Reputation: 2125

Spring Error form not displayed

I created a Spring MVC Project but the errors of form are not displayed .Why?
I try to create a simple form.This is the code of my Project.The project works but in jsp the error are not dispayed..Where did I go wrong?Thanks

Student.java

package coreservlets;

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

public class Student {

@Size(min=4,max=5,message="Size wrong")
@NotNull
private String name;
@Size(min=4,max=5,message="Size wrong")
@NotNull
private Integer age;
@Size(min=4,max=5,message="Size wrong")
@NotNull
private Integer id;

public String getName(){return name;}//getName

public void setName(String name){this.name=name;}//setName

public Integer getAge(){return age;}//getAge

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

public Integer getId(){return id;}//getId

public void setId(Integer id){this.id=id;}//setId

}//Student

StudentController.java

package coreservlets;

import javax.validation.Valid;

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;

@Controller
public class StudentController {

@RequestMapping(value="/",method=RequestMethod.GET)
public ModelAndView student(){

    return new ModelAndView("student", "command", new Student());

}//student 

@RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(@ModelAttribute @Valid Student student,ModelMap model){

    model.addAttribute("name",student.getName());
    model.addAttribute("age",student.getAge());
    model.addAttribute("id",student.getId());

    return "result";
}//addStudent

}//StudentController

student.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>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="post" action="/SpringMVCFormExample/addStudent" >

<table>
<tr>
    <td><form:label path="name">Name</form:label></td>
    <td><form:input path="name"/></td>
    <form:errors path="name" />
</tr>

<tr>
    <td><form:label path="age">Age</form:label></td>
    <td><form:input path="age"/></td>
    <form:errors path="age" />
</tr>

<tr>
    <td><form:label path="id">Id</form:label></td>
    <td><form:input path="id"/></td>
    <form:errors path="id" />
</tr>

<tr>
    <td colspan="2">
        <input type="submit" value="Submit"/>
    </td>
</tr>

</table>
</form:form>

result.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/html/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
     <td>Name</td>
     <td>${name}</td>   
</tr>

<tr>
    <td>Age</td>
    <td>${age}</td>
</tr>

<tr>
    <td>Id</td>
    <td>${id}</td>
</tr>
</table>

</body>
</html>

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" 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">

 <display-name>Spring MVC Form</display-name>

<servlet>
    <servlet-name>SpringMVCForm</servlet-name>
    <servlet-class>
       org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>SpringMVCForm</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


</web-app>

SpringMVCForm-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: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.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

  <context:component-scan base-package="coreservlets" />

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

Upvotes: 0

Views: 225

Answers (3)

geoand
geoand

Reputation: 64011

The following code will return the user to the student form when a validation error occurs. When there is no validation error, the result template will be shown

@RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(@Valid Student student, BindingResult errors, Model model){
    if (errors.hasErrors()) {
        return "student";
    }
    model.addAttribute("name",student.getName());
    model.addAttribute("age",student.getAge());
    model.addAttribute("id",student.getId());

    return "result";
}

You need to make sure that BindingResult errors is positioned exactly after @ModelAttribute @Valid Student student

Check out this and this tutorial for more info.

On another note, you should probably be redirecting the user after a successful POST. See this for more details

Upvotes: 0

Rafik BELDI
Rafik BELDI

Reputation: 4158

If you set the validation at model level you should use BindingResult:

 @RequestMapping(value="/addStudent", method=RequestMethod.POST)
    public String addStudent(@ModelAttribute @Valid Student student,ModelMap model,BindingResult   errors){
    if (errors.hasErrors()) {
                List<FieldError> lerr = errors.getFieldErrors();
                for (FieldError err: lerr) {
                    // manage the errorrs   
                }
            }
    model.addAttribute("name",student.getName());
    model.addAttribute("age",student.getAge());
    model.addAttribute("id",student.getId());

    return "result";
    }

if you want to handle validation at client level you can jquery.validate.js.

Upvotes: 0

Sunil Khokhar
Sunil Khokhar

Reputation: 370

Use BindingResult class as parameter in your method. your method should look like this

public String addStudent(@ModelAttribute @Valid Student student,ModelMap model,BindingResult result)

Spring MVC will validate the model object annotated by the @Valid annotation after binding its properties with inputs from JSP form that uses Spring’s form tags. Any constraint violations will be exposed as errors in the BindingResult object, thus we can check the violation in the controller’s method like this:

if (result.hasErrors()) {

// form validation error

} else {

// form input is ok

}

Upvotes: 1

Related Questions