java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring4 validation校验无效

Spring4下validation数据校验无效(maven)的解决

作者:JavaLitterBoy

这篇文章主要介绍了Spring4下validation数据校验无效(maven)的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringMVC4使用数据校验的时候需要使用hibernate-validator的包

第一步添加依赖

    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>2.0.0.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.4.1.Final</version>
    </dependency>

第二步添加校验注解

package com.demo.model;
/*
* spring4 用hibernate中的validation
* 
* */
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Size;
public class User {
    private String username;
    private String password;
    private String nickname;
    private String email;
    public User(){
    }
    public User(String username, String password, String nickname, String email) {
        this.username = username;
        this.password = password;
        this.nickname = nickname;
        this.email = email;
    }
    @NotBlank(message = "用户名不能为空")
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    @Size(min = 6,max = 20,message = "密码为6-20位")
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    @Email(message = "请输入合法的邮箱")
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

第三步在控制器中对指定参数进行校验注解

 注:BindingResult 必须紧跟在@Validate

    //@Validated指定验证对象 BindingResult紧跟Validated
    @RequestMapping(value="/add",method = RequestMethod.POST)
    public String add(@Validated User user, BindingResult br){
        System.out.println(br);
        System.out.println(br.getErrorCount());
        if(br.hasErrors())
            return "user/add";
        users.put(user.getUsername(),user);
        return "redirect:/user/users";
    }

注:这个配置也会影响到校验是否生效

<mvc:annotation-driven/>

SpringBoot-----数据验证validation(实战中,不推荐使用)

1、定义错误信息

在resources/下创建名称为ValidationMessages.properties

member.mid.notnull.error=用户名不允许为空
member.mid.email.error=用户名的注册必须输入正确的邮箱
member.mid.length.error=用户名的格式错误

2、给Vo类添加注解

package com.zemel.micorboot.vo;
import java.io.Serializable;
import java.util.Date;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
public class Member implements Serializable{
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 @NotNull(message="{member.mid.notnull.error}")
 @Email(message="{member.mid.email.error}")
 @Length(min=6,message="{member.mid.length.error}")
 private String mid;
 private Integer age;
 private Double salary;
 private Date birthday;
 public String getMid() {
  return mid;
 }
 public void setMid(String mid) {
  this.mid = mid;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
 public Double getSalary() {
  return salary;
 }
 public void setSalary(Double salary) {
  this.salary = salary;
 }
 public Date getBirthday() {
  return birthday;
 }
 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }
}

3、控制添加验证

@Valid Member vo, BindingResult result
package com.zemel.micorboot.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zemel.micorboot.base.AbstractBaseController;
import com.zemel.micorboot.vo.Member;
 
@Controller
public class MemberController extends AbstractBaseController {
 @GetMapping("/addPre")
 public String addPre(){
  return "message/member_add";
 }
 
 @GetMapping("/add")
 @ResponseBody
 public Object add(@Valid Member vo, BindingResult result){
  System.out.println("【ADD方法】"+result.hasErrors());
  
  if(result.hasErrors()){
   List<ObjectError> list = result.getAllErrors();
   list.forEach(oe -> {
    
   });
   return result.getAllErrors();
  }
  return vo; 
 }
}

4、访问结果

[{"codes":["Email.member.mid","Email.mid","Email.java.lang.String","Email"],"arguments":[{"codes":["member.mid","mid"],"arguments":null,"defaultMessage":"mid","code":"mid"},[],{"defaultMessage":".*","arguments":null,"codes":[".*"]}],"defaultMessage":"ç¨æ·åç注åå¿é¡»è¾å¥æ­£ç¡®çé®ç®±","objectName":"member","field":"mid","rejectedValue":"xx","bindingFailure":false,"code":"Email"}]

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文