springBoot系列教程06:參數驗證及驗證信息國際化


在springboot應用中要驗證參數是否正確很簡單,web應用已經包含了validation的

 

1.定義需要被驗證的參數實體,並用注解標明錯誤類別和錯誤信息

package com.xiao.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

/**
 * @since 2017年12月7日 下午2:17:42
 * @author 肖昌偉 317409898@qq.com
 * @description
 */
public class User implements Serializable {
    private static final long serialVersionUID = 4167869185651158701L;

    private Long id;
    @NotEmpty(message="{error.name}")
    private String name;
    @NotEmpty(message="密碼不能為空")
    private String pwd;
    private String salt;

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birthDay = new Date();

    private List<Photo> pics = new ArrayList<Photo>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public Date getBirthDay() {
        return birthDay;
    }

    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }

    public List<Photo> getPics() {
        return pics;
    }

    public void setPics(List<Photo> pics) {
        this.pics = pics;
    }

}

有兩種方式指定錯誤信息

a:直接在messeage里面指定信息,但是這不利於國際化或者提示信息的變動

b:在錯誤消息里面執行,便於管理及國際化

如上,error.name即需要在配置文件中指定

默認的文件為ValidationMessages.properties 

 

在controller中使用如下:

@RequestMapping(value = "/json/test")
    public Result jsonTest(@Valid User user) {
        System.out.println(JSON.toJSONString(user));
        return new Result(user);
    }

注意 必須加上@Valid 注解,否則不生效

 

測試效果如下:

 

 

具體的錯誤信息展示可以根據需要進行格式輸出,但是,錯誤的內容就是message里面或者properties文件中指定的內容

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM