zoukankan      html  css  js  c++  java
  • spring boot快速入门 6: 表单验证

    廖师兄源码: https://gitee.com/liaoshixiong/girl

    样例:拦截所有未满18岁的女生

    第一步:在girl实体类中:添加注解 @Min(value=18 ,message = "未成年少女禁止入内!")

    package com.payease.domain;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.validation.constraints.Min;
    
    /**
     * Created by liuxiaoming on 2017/11/6.
     */
    @Entity
    public class Girl {
    
        @Id
        @GeneratedValue
        private int id;
    
        private String cupSize;
    
        @Min(value=18 ,message = "未成年少女禁止入内!")
        private int age;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getCupSize() {
            return cupSize;
        }
    
        public void setCupSize(String cupSize) {
            this.cupSize = cupSize;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
    
    
    }

    第二步:GirlResposity

    package com.payease.respository;
    
    import com.payease.domain.Girl;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import java.util.List;
    
    /**
     * Created by liuxiaoming on 2017/11/6.
     */
    public interface GirlRespository extends JpaRepository<Girl,Integer>{
    }

    第三步:在controller 中 添加注解:@Valid

     @Autowired
        private GirlRespository girlRespository;    
    
       /**
         * 创建一个女生
         */
        @PostMapping("/girls")
        public Girl girlAdd(@Valid Girl girl, BindingResult bindingResult){
            if(bindingResult.hasErrors()){
                System.out.println(bindingResult.getFieldError().getDefaultMessage());
                return null;
            }
            girl.setCupSize(girl.getCupSize());
            girl.setAge(girl.getAge());
            return girlRespository.save(girl);
        }

    第四步:postman提交

  • 相关阅读:
    PHP联接MySQL
    PHP分页及原理
    两种ajax的方法
    Mysql 数据库 操作语句
    HTTP状态码对照表 HTTP response codes
    HTTP请求中POST与GET的区别
    Django模板导入和替换、以及对数据库的增加、查看
    Django模板(filter过滤器{{ }}与tag标签{% %}应用)
    Django视图层
    Diango路由控制
  • 原文地址:https://www.cnblogs.com/liuxiaoming123/p/7798679.html
Copyright © 2011-2022 走看看