Spring MVC 3表单验证注释被忽略了吗?

时间:2012-09-16 16:15:49

标签: java validation spring-mvc annotations

我正在学习如何使用本教程进行简单的表单验证: http://www.raistudies.com/spring/spring-mvc/form-validation-spring-mvc-3-hibernate-validator-jsr-303/

问题是,当我输入无效数据(空白字段)时,任何地方的用户都没有错误。 result.hasErrors()总是产生错误。

我制作了以下代码:

IndexController.java:

package pl.aadamczyk.springtest.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.aadamczyk.springtest.beans.LoginBean;

@Controller
@RequestMapping("/index")
public class IndexController
{   
    @RequestMapping(method = RequestMethod.GET)
    public String getIndex(ModelMap model)
    {
        LoginBean loginBean = new LoginBean();
        model.addAttribute("loginBean", loginBean);

        return "index";
    }
}

+ LoginController.java:

package pl.aadamczyk.springtest.controllers;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
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 pl.aadamczyk.springtest.beans.LoginBean;
import pl.aadamczyk.springtest.validators.LoginValidator;

@Controller
@RequestMapping("/login")
public class LoginController
{
    private LoginValidator loginValidator;

    private LoginValidator getValidator()
    {
        return loginValidator;
    }

    @Autowired
    public void setValidator(LoginValidator loginValidator)
    {
        this.loginValidator = loginValidator;
    }

    @RequestMapping(method= RequestMethod.POST)
    public String login(@Valid @ModelAttribute(value="loginBean") LoginBean loginBean,
                        ModelMap model,
                        BindingResult result)
    {
        System.out.println(result.hasErrors()); // always false

        loginValidator.validate(loginBean, result);

        return "redirect:index.html";

    }
}

+ LoginValidator.java

package pl.aadamczyk.springtest.validators;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import pl.aadamczyk.springtest.beans.LoginBean;

@Component
public class LoginValidator implements Validator
{
    @Override
    public boolean supports(Class<?> type)
    {
        return LoginBean.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object o, Errors errors)
    {

    }
}

LoginBean.java:

package pl.aadamczyk.springtest.beans;

import org.hibernate.validator.Length;
import org.hibernate.validator.NotEmpty;

public class LoginBean
{
    @NotEmpty(message="Username is mandatory.")
    @Length(min=3,max=25,message="Username must be between 3 and 25 characters length")
    private String username;

    @NotEmpty(message="Password field is mandatory.")
    @Length(min=3,max=25,message="Password must be between 5 and 25 characters length")
    private String password;

    // getters+setters skipped
}

index.jsp的一部分:

<form:form method="post" action="login.html" modelAttribute="loginBean">
    <table>
        <tr>
            <td>Login:</td>
            <td><form:input path="username"/></td>
            <td><form:errors path="username"/></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><form:input path="password"/></td>
            <td><form:errors path="password"/></td>
        </tr>
        <tr>
            <td colspan="3"><button type="submit">Login</button></td>
        </tr>
    </table>
</form:form>

dispatcher-servlet的重要内容:

<context:annotation-config /> 
<context:component-scan base-package="pl.aadamczyk.springtest"/>
<mvc:annotation-driven/>

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

pom.xml依赖项:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-asm</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-instrument</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-instrument-tomcat</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jms</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc-portlet</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-struts</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.1.2</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>3.0.0.ga</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
</dependency>

2 个答案:

答案 0 :(得分:1)

要使验证正常运行,请确保您的类路径中有{strong>最近版本的hibernate-validator

要在A JSP页面中打印错误,请使用以下内容

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
...

 <spring:hasBindErrors name="person">
    <div class="error">
        <c:forEach var="error" items="${errors.allErrors}">
            <p>Errors ${error.defaultMessage}</p>
        </c:forEach>
    </div>
</spring:hasBindErrors>

您还需要类路径中的jstlspring-webmvc库。

答案 1 :(得分:1)

BindingResult 必须在经过验证的模型对象之后才会出现,否则 Spring 将无法验证对象并抛出异常。

Spring 看到 @Valid 时,它会尝试为要验证的对象找到验证器。如果您启用了注释驱动,Spring会自动选择验证注释。然后Spring调用验证器并将任何错误放在 BindingResult 中,并将 BindingResult 添加到视图模型中。