1 Introducing spring Boot validate maven dependency
<!--verification- <dependency> <groupId>org.hibernate.validator</groupId> < Artifactid>hibernate-validator</artifactid> </dependency> |
2 input parameter Model DTO
Package Com.example.demo.input;import Javax.validation.constraints.notempty;import Javax.validation.constraints.Size; Public classaccountcreateinput {@Size (min=6, max=30,message ="account name length must be between 6 and 30")PrivateString LoginName; @NotEmpty (message ="Password cannot be empty")PrivateString loginpwd;PrivateString Realname; PublicString Getloginname () {returnLoginName; } Public voidSetloginname (String loginName) { This. loginName = LoginName; } PublicString Getloginpwd () {returnLoginpwd; } Public voidSetloginpwd (String loginpwd) { This. loginpwd = loginpwd; } PublicString Getrealname () {returnRealname; } Public voidSetrealname (String realname) { This. realname = Realname; }} |
3 Enable unified validation error handling. When the parameter model validation does not pass, it throws
Methodargumentnotvalidexception
Package Com.example.demo.config;import Com.example.demo.infrastructure.friendlyexception;import Com.example.demo.infrastructure.unauthorizedexception;import Com.example.demo.Infrastructure.http.ResultModel; Import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.validation.bindingresult;import Org.springframework.validation.fielderror;import org.springframework.web.bind.MethodArgumentNotValidException; Import Org.springframework.web.bind.annotation.controlleradvice;import Org.springframework.web.bind.annotation.exceptionhandler;import Org.springframework.web.bind.annotation.responsebody;import javax.servlet.http.httpservletrequest;@ Controlleradvice Public classGlobalexceptionhandler {PrivateLogger Logger = Loggerfactory.getlogger ( This. GetClass ()); @ExceptionHandler (value= Exception.class) @ResponseBody PublicResultmodel Jsonerrorhandler (httpservletrequest req, Exception e) {//Friendly tips error if(e instanceof friendlyexception) {Logger.info (E.getmessage ());returnResultmodel.internalservererror (E.getmessage ()); }//Permissions Check Else if(e instanceof unauthorizedexception) {Logger.info (E.getmessage ());returnResultmodel.unauthorized (E.getmessage ()); } //Global uniform checksum Else if(e instanceof methodargumentnotvalidexception) {methodargument Notvalidexception ex = (methodargumentnotvalidexception) e; Bindingresult result = Ex.getbindingresult (); StringBuffer sb = new stringbuffer (); for (Fielderror error:result.getFieldErrors ()) {String field = Error.getfield (); String msg = Error.getdefaultmessage (); String message = String.Format ("%s:%s", field, MSG); Sb.append (message); } return resultmodel.internalservererror (sb.tostring ()); } //Unknown exception Else{Logger.error (E.getmessage (), E);returnResultmodel.internalservererror (E.tostring ()); } }} |
4 Annotate input parameters in the controller that need to be validated, add @validated annotations before the Createaccountinput parameter
Package Com.example.demo.controller;import Com.example.demo.infrastructure.http.resultmodel;import Com.example.demo.domain.account;import Com.example.demo.input.accountcreateinput;import Com.example.demo.service.iaccountservice;import Io.swagger.annotations.api;import Io.swagger.annotations.apioperation;import Io.swagger.annotations.apiparam;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.validation.annotation.validated;import Org.springframework.web.bind.annotation.*;import Org.slf4j.logger;import org.slf4j.loggerfactory;import java.util.List; @Api (value="Account API", Description ="API of account") @RestController @requestmapping ("/account") Public classAccountController {PrivateLogger Logger = Loggerfactory.getlogger ( This. GetClass ()); @Autowired Iaccountservice Accountservice; @ApiOperation (value="Account Index list", notes ="Account list Information") @RequestMapping (value="/index", method = Requestmethod.get) PublicResultmodel index () {list<account> rows = This. Accountservice.findall ();returnResultmodel.ok (rows); } @ApiOperation (value="Create a Account", notes ="A account name") @RequestMapping (value="/create", method = Requestmethod.post) PublicResultmodel Create (@ApiParam (name ="Model",value="Input a account entity") @RequestBody @Validated Accountcreateinput model) { This. accountservice.create (model); Account entity = This. Accountservice.findaccountbyname (Model.getloginname ());returnResultmodel.ok (entity); } @ApiOperation (value="Find account by name", notes ="Find account based on login name") @RequestMapping (value="/query", method = Requestmethod.get) PublicResultmodel query (@RequestParam String name) { This. Logger.info (String.Format ("url:/account/query?name=%s", name)); list<account> rows = This. Accountservice.findallbyname (name);returnResultmodel.ok (rows); }} |
5 result of last swagger request:
Request parameter, password is not filled
Response Result:
Spring boot input parameter uniform checksum