java - spring-mvc 表单验证

标签 java validation spring-mvc

我在 spring-mvc 中有一个带有表单验证的程序。

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.evgeny.spring.form.beans.Person;

@Controller
public class FormController {

    @RequestMapping(method = RequestMethod.GET,value="some")
    public ModelAndView goRegistrate(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("person", new Person());
        mav.setViewName("regForm");
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST,value="reg")
    public ModelAndView handleForm(@Valid Person person){
        person.setId(person.getId()+1);
        person.setName(person.getName()+"test");
        return new ModelAndView("view","personPlus",person);
    }
}

人 bean :

public class Person {
    @Size(max=100, min=0,message="0 to 100")
    private int id;
    private String name;

    public Person(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public Person() {
        this.id = 1;
        this.name = "No name";

    }

    //Getters and Setters...
}

形式:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <sf:form method="post" modelAttribute="person" action="reg.htm">
        <sf:input path="id" id="personId"/>
        <sf:input path="name"/>
        <input type="submit" value="Submit"/>
    </sf:form>
</body>
</html>

验证不起作用。当我输入 0 到 100 范围之外的值时,程序将继续。

我的 spring 配置文件中没有。当我添加它时,我得到:

Error creating bean with name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is javax.validation.ValidationException: Could not create Configuration.

最佳答案

您定义了 validator bean 吗?

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

您可能还需要添加验证依赖项..

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>com.springsource.javax.validation</artifactId>
    <version>1.0.0.GA</version>
  </dependency>

关于java - spring-mvc 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7164394/

相关文章:

java - WEKA - JDBC 连接异常

java - 使用screencap截屏时出现0字节文件

java - 对象池: howto

Java:用于加载类的星号

android - laravel 5.4 chrome for android 不显示验证错误

java - 验证 double 值在两个值之间并且 GUI 打开两个 JFrame

javascript - 语义 UI 正则表达式解析器似乎无法正常工作

java - 从文件系统中的任何位置使用 Spring-Boot 和 Spring-MVC 提供文件服务

spring-mvc - HttpMediaTypeNotAcceptableException : Could not find acceptable representation spring mvc

java - 使用 Java 配置将 Spring MVC 拦截器绑定(bind)到 URL