First of all, say the application scenario, such as the reception of a parameter, we must be in the background to judge, such as ID can not be empty, phone number can not be less than 11 and so on. If one judge in the service layer is not to be exhausted personally. The code is not concise, at this time we will certainly think of using annotations ah. The Javax package provides the ability to validate parameters. Enough to meet our needs. Add annotations on the object is not finished, there are validation, for example, I add annotations to the object, we do not verify or no use, the verification method is definitely our own definition, if the error, we write a method to get these error messages are either written to the log, or back to the front.
First we need the dependency of these classes
<!--Annotations Validator-- <dependency> <groupId>javax.validation</groupId> < artifactid>validation-api</artifactid> <version>1.1.0.Final</version> </ dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId> hibernate-validator</artifactid> <version>5.2.4.Final</version> </dependency> <!--Toolkit Tools-- <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>commons-codec</groupId> < artifactid>commons-codec</artifactid> <version>1.10</version> </dependency >
View Code
Write a validation tool class (This tool class can be taken directly, regardless of how it is implemented)
PackageCom.mmall.util;Importcom.google.common.base.Preconditions;Importcom.google.common.collect.Lists;ImportCom.google.common.collect.Maps;Importcom.mmall.exception.ParamException;Importorg.apache.commons.collections.MapUtils;Importjavax.validation.ConstraintViolation;Importjavax.validation.Validation;ImportJavax.validation.Validator;Importjavax.validation.ValidatorFactory;Importjava.util.Collection;Importjava.util.Collections;ImportJava.util.Iterator;ImportJava.util.LinkedHashMap;ImportJava.util.Map;ImportJava.util.Set; Public classBeanvalidator {Private StaticValidatorfactory validatorfactory =validation.builddefaultvalidatorfactory (); //check for an object Public Static<T> map<string, string>Validate (T T, Class ... groups) {Validator Validator=Validatorfactory.getvalidator (); Set Validateresult=validator.validate (t, groups); if(Validateresult.isempty ()) {returnCollections.emptymap (); } Else{Linkedhashmap Errors=Maps.newlinkedhashmap (); Iterator Iterator=Validateresult.iterator (); while(Iterator.hasnext ()) {constraintviolation violation=(constraintviolation) iterator.next (); Errors.put (Violation.getpropertypath (). toString (), Violation.getmessage ()); } returnerrors; } } //check a list object Public StaticMap<string, string> validatelist (collection<?>collection) {Preconditions.checknotnull (collection); Iterator Iterator=Collection.iterator (); Map errors; Do { if(!Iterator.hasnext ()) { returnCollections.emptymap (); } Object Object=Iterator.next (); Errors= Validate (Object,NewClass[0]); } while(Errors.isempty ()); returnerrors; } //use a method to encapsulate the above two methods. We can choose to use this method and then go to map, log the map error message to the logs, and throw the exception Public StaticMap<string, string>Validateobject (object First, Object ... objects) {if(Objects! =NULL&& objects.length > 0) { returnValidatelist (Lists.aslist (First, objects)); } Else { returnValidate (First,NewClass[0]); } } //we can also choose to use this method to throw the anomaly directly Public Static voidCheck (Object param)throwsparamexception {Map<string, string> map =beanvalidator.validateobject (param); if(Maputils.isnotempty (map)) {Throw Newparamexception (map.tostring ()); } }}
View Code
Explain the above method, which means that the controller invokes the two methods of the tool class above. One is to return the map, and one is to throw the exception directly. The map contains error messages. Because the note contains the error message. Then our global catch Exception class captures the information inside. It's okay to be confused. Tool class only. Take it up and use it, a copy of the paste. Flattered ~ ~ ~
Write an entity class
PackageCom.mmall.model;ImportLombok. Data;ImportOrg.hibernate.validator.constraints.NotBlank;ImportJavax.validation.constraints.NotNull;/*** Created by knocking the code out of the Kaka * on 2018/3/24 23:59.*/@Data Public classTestvo {@NotNullPrivateInteger ID; @NotBlankPrivateString name; PublicTestvo (Integer ID, String name) { This. ID =ID; This. Name =name; }}
View Code
And then the controller layer tests
@RequestMapping ("Test.json") public Modelandview SS () { Beanvalidator.check ( New Testvo (null,null)); New HashMap (); Map.put ("name", "Lzh"); Map.put ("Age",N); Modelandview View=new modelandview ("Jsonview", map); return view; }
View Code
Will throw an exception directly. Of course, if the exception information provided by Javax does not satisfy you, you can also customize it. Self-Baidu put ....
Parameter test of SPRINGMVC