Spring MVC 3 Form Validator not displaying Error message in .jsp

ramlax picture ramlax · Nov 5, 2013 · Viewed 15.3k times · Source

I entered in Spring Web MVC Framework not long ago thus I am a complete beginner. Right now I am implementing a basic form for my first web application.

In the same time I would like to say that I've been seeking a solution for my problem for whole day. I apolgize in advance if the solution for similar problem was already published.

Source code:

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

    <context:component-scan base-package="si.src.controllers" />
    <context:component-scan base-package="si.src.validators" />

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

index.jsp

<!-- language: lang-jsp -->
<html>
<head>
    <title>Spring 3.0 MVC Series - Index</title>
</head>
<body>
    <br>
    <div align='center'>
        <p>
        <h1>Example - Spring Application</h1>
        The "index.jsp" is the entry point for our application.
        This is my first test. Work!            
        <p>
        <a href="login.html">Welcome! Click Here to Login</a>           
    </div>      
</body>
</html>

login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
    <title>Spring Sample - Login Page</title>
</head>
<body>
    <h3>Login Page</h3><br>
    <form:form id="form" method="post" commandName="loginForm">
        <form:errors path="*" cssClass="errorblock" element="div" />
        <table>
            <tr>
                <td><form:label path="username">Username</form:label></td>
                <td><form:input path="username" /></td>
                <td><form:errors path="username" cssClass="error"/></td>
            </tr>
            <tr>
                <td><form:label path="username">Password</form:label></td>
                <td><form:input path="password" /></td>
                <td><form:errors path="password" cssClass="error"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Sign in" /></td>
            </tr>
        </table>
    </form:form>
</body>
</html>

LoginFormController.java

package si.src.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;

import si.src.logic.Login;
import si.src.validators.LoginValidator;

@Controller
@RequestMapping(value="/login")
public class LoginFormController extends SimpleFormController{

    public LoginFormController(){
        setCommandClass(Login.class);   //Form's values will store into the Login object    
        setCommandName("loginForm");    //If HTML form action value with named "loginForm" is sumbitted, Spring will forward request to this form controller
    }

    @RequestMapping(method=RequestMethod.POST)
    protected ModelAndView onSubmit(HttpServletRequest request,
        HttpServletResponse response, Object command, BindException errors) throws Exception{

        LoginValidator validator = new LoginValidator();        
        Login userLogin = (Login) command;
        validator.validate(userLogin, errors.getBindingResult());

        if(errors.hasErrors()){
            userLogin.setUsername("");
            userLogin.setPassword("");
            System.out.println("Ne");
            return new ModelAndView("login","loginForm", userLogin);

        }
        else{
            System.out.println(userLogin);
            System.out.println(userLogin.getUsername() + " " + userLogin.getPassword());    
            return new ModelAndView("success","userLogin", userLogin);
        }
    }

    protected Object formBackingObject(HttpServletRequest request) throws Exception {   
        //Initialize the values in the form. Not necessary
        Login userLogin = new Login();
        userLogin.setUsername("Admin");
        return userLogin;
    }

}

LoginValidator.java

package si.src.validators;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.ValidationUtils;

import si.src.logic.Login;

public class LoginValidator implements Validator{

    public boolean supports(Class aClass) {
        //just validate the Login instances
        return Login.class.isAssignableFrom(aClass);
    }

    public void validate(Object obj, Errors errors) {
        Login login = (Login) obj;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username","required-username", "Enter username");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password","required-password", "Enter password");    
    }   
}

Login.java

package si.src.logic;

public class Login {

    private String username;
    private String password;

    public Login(){}

    public void setUsername(String username){
        this.username=username;
    }

    public String getUsername(){
        return username;
    }

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

    public String getPassword(){
        return password;
    }   
}

I suppose the error messages obtained by LoginValidator object are not correctly "binded" with my login.jsp file. I guess that is the reason why the error messages i.e "Enter username" and "Enter password" don't show up when my form is poorly fulfilled.

My question is: Why the error messages are not showing up in a login.jsp?

Answer

user2983066 picture user2983066 · Feb 17, 2014

I have similar problem. Also I have changed the type of return, but I have the need to trasfert date from controller to JSP. I use object model, but I have the same result of object modelandview.

How can I transfer data without losing the display of form:errors?

@RequestMapping(value="/addCaregiver", method= RequestMethod.POST)
public String addCaregiver(@ModelAttribute("caregiver") @Valid  
Caregivers caregiver, BindingResult result,Principal principal, Model model){


caregiverValidator.validate(caregiver, result);
if(result.hasErrors()){

model.addAttribute("caregivers",pp.getCaregiverses(principal.getName()));
model.addAttribute("error", "true");
model.addAttribute("caregiver", new Caregivers());
return "caregiver";
        }
return "intro";
}

I solved, don't create a new istance, I delete this row:

model.addAttribute("caregiver", new Caregivers());