繁体   English   中英

spring-mvc表格验证

[英]spring-mvc form validation

我在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);
    }
}

人豆:

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时,程序将继续。

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

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.

您是否定义了验证器bean?

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

您可能还需要添加validation依赖项。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM