2010-10-27 28 views
16

Necesito ayuda. Soy principiante en jsp, MVC. Quiero validar la entrada del formulario con el validador personalizado en Spring 3 MVC.Spring 3 MVC: Mostrar mensaje de validación con validador personalizado

Mi clase de validador

package validators; 

import models.UserModel; 

import org.springframework.stereotype.Component; 
import org.springframework.validation.Errors; 
import org.springframework.validation.ValidationUtils; 
import org.springframework.validation.Validator; 
@Component 
public class UserValidator implements Validator { 

    @Override 
    public boolean supports(Class clazz) { 
     return UserModel.class.isAssignableFrom(clazz); 
    } 

    @Override 
    public void validate(Object target, Errors errors) { 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstname", "Enter firstname."); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "Enter surname."); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "Enter login."); 

    } 

} 

clase controlador

package controllers; 

import java.util.ArrayList; 
import models.UserModel; 
import org.springframework.stereotype.Controller; 
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 org.springframework.web.servlet.ModelAndView; 
import validators.UserValidator; 
import database.UserDB; 


@Controller 
public class UserController { 

@RequestMapping(value="pouzivatel/new", method=RequestMethod.POST) 
    public ModelAndView newUser(@ModelAttribute UserModel user, BindingResult result){ 
     UserValidator validator = new UserValidator(); 
     validator.validate(user, result); 
     if(result.hasErrors()){ 
     return new ModelAndView("/user/new","command",user); 

     } 
     ... 
} 

Modelo de usuario

package models; 

public class UserModel { 
    private String firstname=""; 
    private String surname=""; 

    public String getFirstname() { 
     return firstname; 
    } 
    public String getSurname() { 
     return surname; 
    } 

    public void setFirstname(String firstname) { 
     this.firstname = firstname; 
    } 
    public void setSurname(String surname) { 
     this.surname = surname; 
    } 

} 

JSP veiw new.jsp que se encuentra en el directorio/WEB-INF/usuario (se solo forma)

<form:form method="post" action="new.html"> 
      <fieldset> 
       <table> 
        <tr> 
        <td> 
         <form:label path="firstname">FirstName</form:label> 
        </td> 
        <td> 
         <form:input path="firstname" /> 
         <form:errors path="firstname" /> 
        </td> 
        </tr> 
        <tr> 
        <td> 
         <form:label path="surname">Surname</form:label> 
        </td> 
        <td> 
         <form:input path="surname" /> 
         <form:errors path="surname" /> 
        </td> 
        </tr> 
       </table> 
      </fieldset> 
      <div> 
       <button type="submit" id="btOk">Ok</button> 
      </div> 
</form:form> 

despachador 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="controllers" /> 
    <context:component-scan base-package="validators" /> 

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

</beans> 

El problema es que un mensaje de validación pantalla a la vista. La validación es exitosa y en variable resut (BindingResult) son errores. Controlador de retorno sigue es parte del código

if(result.hasErrors()){ 
     return new ModelAndView("/user/new","command",user); 

Otra forma es la validación uso de anotación (I preffer validador personalizado), pero ¿por qué no puedo ver los mensajes de validación a la vista, cuando los campos de entrada están vacíos.

¿Puede darme un ejemplo de cómo hacerlo bien?

Gracias por su respuesta.

Respuesta

20

Esto sucede debido a la falta de coincidencia entre el modelo por defecto los nombres de atributos a la vista y el controlador:

  • Cuando se escribe sin <form:form>modelAttribute (o commandName) atributo, se utiliza el modelo predeterminado atributo de nombre command.
  • Cuando escribe @ModelAttribute UserModel user en su controlador, asume que el nombre de este atributo es un nombre de clase descapitalizado, es decir, userModel.

Es decir, los mensajes de error producidos por validador están obligados a modelar atributo llamado userModel, mientras que su punto de vista trata de mostrar los errores en el modelo de atributos command.

Debe establecer un nombre de atributo de modelo explícitamente, ya sea en la vista (<form:form modelAttribute = "userModel" ...>) o en el controlador (@ModelAttribute("command")).

+0

Muchas gracias, está funcionando ahora. – Jerry

Cuestiones relacionadas