5th-Building a Spring Web application-parsing of validate annotation background check in spring

Source: Internet
Author: User

Parsing of validate annotation background check in spring

In the background development process, the validation of parameters becomes an indispensable part of the development environment. For example, the parameter can not be null,email so must conform to the format of email, if manually make if judgment or write regular expression to judge the unintended development efficiency is too slow, in time, cost, quality of the game will inevitably lag behind. So the verification layer is the inevitable result of abstraction, the following is a few solutions.

1. Simple Check Demo

Depend on:

<dependency>    <groupId>javax.validation</groupId>    <artifactId>validation-api</artifactId>    <version>1.1.0.Final</version></dependency>

Student:

Import Javax.validation.constraints.*;import Java.math.bigdecimal;import Java.util.date;public class Student {@Not        Null (message = "name cannot be null") private String name;        @Size (min = 6, max =, message = "address should be between 6-30 characters") Private String address; @DecimalMax (value = "100.00", message = "weight exceeded") @DecimalMin (value = "60.00", message = "eat more Rice") Private B        Igdecimal weight;        Private String Friendname;        @AssertTrue private Boolean Ishavefriend () {return friendname! = null? true:false;        } @Future (message = "Birthday must precede current practice") private Date birthday;        @Pattern (regexp = "^ (. +) @ (. +) $", message = "The format of the mailbox is not valid") private String email;        Public String GetName () {return name;        } public void SetName (String name) {this.name = name;        } public String getaddress () {return address;       } public void Setaddress (String address) {     this.address = address;        } public BigDecimal Getweight () {return weight;        } public void Setweight (BigDecimal weight) {this.weight = weight;        } public String Getfriendname () {return friendname;        } public void Setfriendname (String friendname) {this.friendname = Friendname;        Public Date Getbirthday () {return birthday;        } public void Setbirthday (Date birthday) {this.birthday = birthday;        } public String Getemail () {return email;        } public void Setemail (String email) {this.email = email; }    }

Demotest:

Import Javax.validation.*;import java.math.bigdecimal;import Java.util.arraylist;import Java.util.Date;import Java.util.list;import Java.util.set;public class Demotest {public static void main (string[] args) {Stu            Dent xiaoming = Getbean ();            List<string> validate = Validate (Xiaoming);            Validate.foreach (row, {System.out.println) (row.tostring ());        });            } private static Student Getbean () {Student bean = new Student ();            Bean.setname (NULL);            Bean.setaddress ("Beijing");            Bean.setbirthday (New Date ());            Bean.setfriendname (NULL);            Bean.setweight (New BigDecimal (30));            Bean.setemail ("xiaogangfan163.com");        return bean;        } private static Validatorfactory factory = Validation.builddefaultvalidatorfactory (); public static <T> list<string> validate (T t) {Validator Validator = Factory.getvalidator();            set<constraintviolation<t>> constraintviolations = validator.validate (T);            list<string> messagelist = new arraylist<> (); for (constraintviolation<t> constraintviolation:constraintviolations) {Messagelist.add (ConstraintV            Iolation.getmessage ());        } return messagelist; }    }
Applications in 2.SpringMVC:

The annotation of the entity class is the same as the student class, but the controller will need to make some changes when it is connected to the value:

// 使用@Valid 表明获取到的数据模型需要验证,传入的Errors对象就是验证出错之后的数据对象,包括校验错误的个数,具体的信息等@RequestMapping(value="/register", method=RequestMethod.POST)public String registerForm(        @Valid @ModelAttribute Student stu, Errors error){    logger.info("注册新用户");        if ( error.hasErrors()) {        logger.error("出错啦");    }        stuList.add(stu);    logger.info("注册的用户信息:/n" + stu);        return "login";}

5th-Building a Spring Web application-parsing of validate annotation background check in spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.