码迷,mamicode.com
首页 > 编程语言 > 详细

Spring MVC 表单验证

时间:2014-06-20 23:28:47      阅读:364      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

1. 基于 JSR-303(一个数据验证的规范):

 
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
 
public class User {
 
    private String username;
   
    private String password;
   
    private int age;
 
    @NotBlank(message="用户名不能为空")
    public String getUsername() {
       return username;
    }
 
    public void setUsername(String username) {
       this.username = username;
    }
 
    @NotNull(message="密码不能为null")
    public String getPassword() {
       return password;
    }
 
    public void setPassword(String password) {
       this.password = password;
    }
 
    @Min(value=10, message="年龄的最小值为10")
    public int getAge() {
       return age;
    }
 
    public void setAge(int age) {
       this.age = age;
    }
   
}
<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    
    <mvc:annotation-driven/>
</beans>

 

import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class UserController {
 
    @RequestMapping("login")
    public String login(@Valid User user, BindingResult result) {
       if (result.hasErrors())
           return "user/login";
       return "redirect:/";
    }
   
}

 

使用@NotBlank等注解,然后在要验证的地方使用@Valid 标签。最后验证的结果是在BindingResult 获取,注意据说result 要紧挨着前面的@Valid,而且是一个验证一个BindingResult参数。

 

 

2. 还有就是继承Validator 接口。

 

Spring MVC 表单验证,布布扣,bubuko.com

Spring MVC 表单验证

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/ranger2016/p/3795728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!