1 引入spring boot validate maven 依賴css
<!-- 驗證 --> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> </dependency> |
2 輸入參數 模型 dto html
package com.example.demo.input; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; public class AccountCreateInput { @Size(min=6, max=30,message = "帳號名長度必須在6,30之間") private String loginName ; @NotEmpty(message = "密碼不能爲空") private String loginPwd; private String realName; public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getLoginPwd() { return loginPwd; } public void setLoginPwd(String loginPwd) { this.loginPwd = loginPwd; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } } |
3 啓用統一驗證錯誤處理 。 當參數模型驗證未經過,會拋出 java
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 class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(this.getClass()); @ExceptionHandler(value = Exception.class) @ResponseBody public ResultModel jsonErrorHandler(HttpServletRequest req, Exception e) { // 友好提示錯誤 if (e instanceof FriendlyException) { logger.info(e.getMessage()); return ResultModel.internalServerError(e.getMessage()); } // 權限校驗 else if (e instanceof UnauthorizedException) { logger.info(e.getMessage()); return ResultModel.Unauthorized(e.getMessage()); } // 全局統一校驗 else if(e instanceof MethodArgumentNotValidException ){ MethodArgumentNotValidException 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()); } // 未知異常 else { logger.error(e.getMessage(), e); return ResultModel.internalServerError(e.toString()); } } } |
4 在controller 中標註須要驗證的輸入參數,在CreateAccountInput 參數前,添加@validated 註解web
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 class AccountController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired IAccountService accountService; @ApiOperation(value = "account index list", notes = "帳戶列表信息") @RequestMapping(value = "/index", method = RequestMethod.GET) public ResultModel index() { List<Account> rows = this.accountService.findAll(); return ResultModel.ok(rows); } @ApiOperation(value = "create a account", notes = "a account name") @RequestMapping(value = "/create", method = RequestMethod.POST) public ResultModel create( @ApiParam(name = "model", value = "input a account entity") @RequestBody @Validated AccountCreateInput model) { this.accountService.Create(model); Account entity = this.accountService.findAccountByName(model.getLoginName()); return ResultModel.ok(entity); } @ApiOperation(value = "find account by name", notes = "根據登陸名查找帳戶") @RequestMapping(value = "/query", method = RequestMethod.GET) public ResultModel query(@RequestParam String name) { this.logger.info(String.format("url:/account/query?name=%s ",name)); List<Account> rows = this.accountService.findAllByName(name); return ResultModel.ok(rows); } } |
5 最後swagger 請求時結果:spring
請求參數,密碼不填json
響應結果:api