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”}]

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: