zoukankan      html  css  js  c++  java
  • 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文件中指定的内容

  • 相关阅读:
    C# 数据操作系列
    C# 数据操作系列
    C# 基础知识系列- 17 小工具优化
    C# 基础知识系列- 17 实战篇 编写一个小工具(1)
    计算机网络知识概述
    微信公众号开发:消息处理
    微信公众号开发:服务器配置
    C#调用接口注意要点
    npm安装和Vue运行
    实战spring自定义属性(schema)
  • 原文地址:https://www.cnblogs.com/xiaochangwei/p/8037528.html
Copyright © 2011-2022 走看看