Springmvc using JSR-303 for verification

Source: Internet
Author: User

The following provides a SPRINGMVC calibration scheme, generally no calibration or manual write validator words have to write a lot of code a lot of if judgment, using JSR-303 specification check only need to add the corresponding annotations on the Pojo field to achieve the verification

1. Dependent jar package, I paste the pom directly

<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>< Spring.version>4.1.1.release</spring.version></properties><dependencies><dependency ><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId> <version>2.4.0</version></dependency><dependency><groupId> Com.fasterxml.jackson.core</groupid><artifactid>jackson-databind</artifactid><version> 2.4.0</version></dependency><dependency><groupid>commons-fileupload</groupid> <artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency> <dependency><groupid>javax.servlet</groupid><artifactid>javax.servlet-api</ Artifactid><version>3.1.0</version></dependency><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.1.3. Final</version></dependency><dependency><groupid>org.springframework</groupid> <artifactid>spring-orm</artifactid><version>${spring.version}</version></dependency ><dependency><groupid>org.springframework</groupid><artifactid>spring-context</ Artifactid><version>${spring.version}</version></dependency><dependency><groupid >org.springframework</groupid><artifactid>spring-web</artifactid><version>${ spring.version}</version></dependency><dependency><groupid>org.springframework</ Groupid><artifactid>spring-webmvc</artifactid><version>${spring.version}</version> </dependency><dePendency><groupid>org.springframework</groupid><artifactid>spring-test</artifactid> <version>${spring.version}</version></dependency><dependency><groupid>org.slf4j </groupid><artifactid>slf4j-log4j12</artifactid><version>1.7.7</version></ Dependency><dependency><groupid>junit</groupid><artifactid>junit</artifactid> <version>4.11</version><scope>test</scope></dependency><dependency>< groupid>org.aspectj</groupid><artifactid>aspectjweaver</artifactid><version>1.8.4 </version></dependency><dependency><groupId>javax.el</groupId><artifactId> Javax.el-api</artifactid><version>3.0.0</version></dependency></dependencies>
2.SPRINGMVC Configuration

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/contexthttp:// www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvchttp:// WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC/SPRING-MVC-3.0.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop.xsd "><!--default annotation map support--><mvc:annotation-driven/> <context:annotation-config/><aop:aspectj-autoproxy/><!--automatically scanned package name--><context:component-scan base-package= " Spring.test.web.controller "/><bean id=" Mappingjacksonhttpmessageconverter "class=" Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter "/></beans>

3. Write the Java code

Build a user class first

public class User {@NotNullprivate string username; @NotNull (message = "Password cannot be null") private string Password;public string Getu Sername () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}
Then build a controller and try it.
@ResponseBody @requestmapping ("/test1") public ajaxresponse validateTest1 (@Valid user user, bindingresult result) { Ajaxresponse ajaxresponse = new Ajaxresponse (); map<string, object> map = new hashmap<> (), if (Result.haserrors ()) {ajaxresponse.setsuccess (false); Ajaxresponse.sethaserrors (True); Map.put ("Errors", result.getallerrors ());} else {map.put ("Now", New Date ()); Map.put ("User", user);} Ajaxresponse.setdata (map); return ajaxresponse;}

This method adds a @valid callout to the first parameter, the second parameter is required and must be followed by the @valid parameter, and the result of the validation is in this result

The method logic is simple, call result.haserrors () to see if there is an error, error, put all the errors into the results returned to the client, if there is no error, return the current time and the user object

And then write a test method, try it.

@Testpublic void Test1 () throws Exception{this.mockmvc.perform (Post ("/validator/test1")). Anddo (print ()); This.mockMvc.perform (Post ("/validator/test1"). Param ("username", "testusername"). Param ("password", "Testpassword" ). Anddo (print ());}

The result of the first request is

{"Success": false, "message": null, "HasErrors": True, "data": [{"Name": "User", "message": "May is not being null"},{"name": " User "," message ":" Password cannot be null "}]}

The second request results in a

{"Success": TRUE, "message": null, "HasErrors": false, "data": {"Now": 1420788232169, "user": {"username": "Testusername" , "password": "Testpassword"}}}

It was obvious that the first request did not have a user name and password two field checksum did not pass, the second was successful

It's still easy to use, but if I don't want to write the IF (Result.haserrors ()) in the Controller method every time, write a section, put the IF in the cut, if there is errors directly return, no more controller method.

@Aspectpublic class Validaspect {@Autowired private Validator Validator; @Around ("@annotation ( org.springframework.web.bind.annotation.ResponseBody) public Object dotest (Proceedingjoinpoint pjp) throws Throwable{methodsignature signature = (methodsignature) pjp.getsignature (); method = Signature.getmethod (); if (! AjaxResponse.class.equals (Method.getreturntype ())) {pjp.proceed ();} object[] args = Pjp.getargs (); annotation[][] annotations = Method.getparameterannotations (); for (int i = 0; i < annotations.length; i++) {if (! Hasvalidannotation (Annotations[i])) {continue;} if (! ( I < annotations.length-1 && args[i+1] instanceof Bindingresult) {//Validation object not followed by Bindingresult, In fact, if there is no need to reach this step continue;} Bindingresult result = (Bindingresult) args[i+1];if (Result.haserrors ()) {Ajaxresponse ajaxresponse = new AjaxResponse () ; ajaxresponse.setsuccess (false); Ajaxresponse.sethaserrors (true); Ajaxresponse.setdata (processerrors (result)); return ajaxresponse;}} return Pjp.proceed ();} Private Boolean HasvalidanNotation (annotation[] annotations) {if (annotations = = null) {return false;} for (Annotation annotation:annotations) {if (Annotation instanceof Valid) {return true;}} return false;} Private list<bindingerror> processerrors (bindingresult result) {if (result! = null && result.haserrors ()) {list<bindingerror> List = new arraylist<bindingerror> (); for (Objecterror error:result.getAllErrors ()) { BindingError be = new BindingError (); Be.setmessage (Error.getdefaultmessage ()); Be.setname (Error.getobjectname ()); List.add (BE);} return list;} return null;}}

Note To add a line <bean class= "Spring.test.web.aop.ValidAspect" to the Springmvc configuration file/>

And then write a method that's similar to the one above.

@ResponseBody @requestmapping ("/test2") public ajaxresponse validateTest2 (@Valid user user, bindingresult result) { Ajaxresponse ajaxresponse = new Ajaxresponse (); map<string, object> map = new hashmap<> (), Map.put ("Now", New Date ()), Map.put ("user", user); Ajaxresponse.setdata (map); return ajaxresponse;}

There is no more judgment haserrors (), and then test it.

Write test mode try it

@Testpublic void Test2 () throws Exception{this.mockmvc.perform (Post ("/validator/test2")). Anddo (print ()); This.mockMvc.perform (Post ("/validator/test2"). Param ("username", "testusername"). Param ("password", "Testpassword" ). Anddo (print ());}

The result of the first request is

{"Success": false, "message": null, "HasErrors": True, "data": [{"Name": "User", "message": "Password cannot be empty"},{"name": "User", " Message ":" May is not NULL "}"}
The second request results in a

{"Success": TRUE, "message": null, "HasErrors": false, "data": {"Now": 1420788479105, "user": {"username": "Testusername" , "password": "Testpassword"}}}
The effect is the same as above.

Of course, this aspect of me is only a demonstration, I intercept the method with responsebody annotations, I will return a uniform format, if you want to return to another view, you have to define the annotations and other parameters.

JSR-303 native support verification annotations are also limited, if you want to implement other validation, you can expand, expand the method on the next time, I also just contact.


Springmvc using JSR-303 for verification

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.