In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "Swagger2+springboot-mvc+hibernate-validator visual view plus parameter example analysis", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Swagger2+springboot-mvc+hibernate-validator visual view plus parameter example analysis" bar!
1 Import the required jar package
Io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2 org.springframework.boot spring-boot-starter-web
two。 Integrate swagger2
Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2 / * * @ author Administrator * @ create 2018-09-12 15:16 * * / @ Configuration@EnableSwagger2public class Swagger2 {@ Bean public Docket createRestApi () {return new Docket (DocumentationType.SWAGGER_2) .apiInfo (apiInfo ()) .select () .apis (RequestHandlerSelectors.basePackage ("com.sungrow.modular.marchine.controller")) Build (PathSelectors.any ()) .build () } private ApiInfo apiInfo () {return new ApiInfoBuilder () .title ("springboot uses swagger to build api documents") .description ("simple and elegant restfun style") .termsOfServiceUrl ("xxx") .version ("2.9.2") .build ();}}
3. Encapsulate the basic request parameter object
Import com.alibaba.druid.util.StringUtils;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.Data;import javax.validation.Valid;import javax.validation.constraints.NotNull / * @ author shihaifeng * @ date 2019-07-29 8:54 * @ basic parameter of desc request header * * / @ ApiModel@Datapublic class RequestBaseParam {/ * user location area code * / / * @ NotNull (message = "area cannot be empty") @ Length (min = 6, max = 6, message = "area length is 6") @ ApiModelProperty (value = "user location area code") private String area * / / * the submitted data is signed by base64, and the symmetric encryption algorithm is used to encrypt the sensitive interface (payment). * / @ ApiModelProperty (value = "data") private String data;*/ / * the md5 verification code generated by the client according to certain rules to ensure the security of data access Sign value 32-bit, not empty * / / @ NotNull (message = "sign cannot be empty") / / @ Length (min = 32, max = 32, message = "sign length 32") @ ApiModelProperty (value = "sign") private String sign; / * * timestamp: the timestamp when the client generates the encrypted value Add a device type timestamp (13 bits) + device type (1 bit) to 14 bits, not empty * / / @ NotNull (message = "tt cannot be empty") / / @ Length (min = 14, max = 14, message = "tt length 14") @ ApiModelProperty (value = "timestamp") private String tt / * login user ID, which can be empty * / @ NotNull (message = "login user ID cannot be empty") @ ApiModelProperty (value = "login user ID") private Integer uid / * * generic: custom request parameter entity object * nested validation must use @ Valid * / @ Valid @ NotNull (message = "custom parameter required") private T t; public String transfer () {StringBuilder builder = new StringBuilder (); if (! StringUtils.isEmpty (tt)) {builder.append ("tt=") .append (tt) .append ("&") } if (uid! = null) {builder.append ("uid=") .append (uid) .append ("&");} return builder.toString ();}}
4. Use aop to intercept exceptions
Package com.sungrow.common.exception;import com.sungrow.common.api.ResultBaseEntity;import org.springframework.http.HttpStatus;import org.springframework.validation.BindException;import org.springframework.validation.BindingResult;import org.springframework.validation.FieldError;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestControllerAdvice / * * @ author shihaifeng * @ date 2019-07-29 16:41 * @ the global processor * / @ RestControllerAdvicepublic class BizExceptionHandler {/ * used by desc to handle parameter binding exceptions receives the exception submitted by the form Return to the client in json format * * @ param e * @ return * / @ ExceptionHandler (BindException.class) @ ResponseStatus (HttpStatus.BAD_REQUEST) public ResultBaseEntity bindException (BindException e) {ResultBaseEntity resultBaseEntity = new ResultBaseEntity () BindingResult bindingResult = e.getBindingResult (); String errorMesssage = "check failed:"; for (FieldError fieldError: bindingResult.getFieldErrors ()) {errorMesssage + = fieldError.getDefaultMessage () + ",";} / * * encapsulate the error result set to the customer * / resultBaseEntity.setResult_code; resultBaseEntity.setResult_msg (errorMesssage) Return resultBaseEntity;} / * block the parameter binding exception submitted by json and return it to the client in json format * @ param e * @ return * / @ ExceptionHandler (MethodArgumentNotValidException.class) @ ResponseStatus (HttpStatus.BAD_REQUEST) public ResultBaseEntity myMethodArgumentNotValidException (MethodArgumentNotValidException e) {ResultBaseEntity resultBaseEntity = new ResultBaseEntity (); BindingResult bindingResult = e.getBindingResult () String errorMesssage = "josn check failed:"; for (FieldError fieldError: bindingResult.getFieldErrors ()) {errorMesssage + = fieldError.getDefaultMessage () + ",";} resultBaseEntity.setResult_code ("400"); resultBaseEntity.setResult_msg (errorMesssage); return resultBaseEntity;}}
4. Added return object encapsulation
Package com.sungrow.common.api;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.Data;import java.io.Serializable;/** * @ author shihaifeng * @ date 2019-07-31 19:04 * @ desc (return encapsulated result set) * * / @ ApiModel (value = "return encapsulated result set") @ Datapublic class ResultBaseEntity implements Serializable {@ ApiModelProperty (value = "result set Encoding, 1: success") private String result_code @ ApiModelProperty (value = "result set message") private String result_msg; @ ApiModelProperty (value = "return class") private T t;}
Quick return result set tool
Package com.sungrow.common.api;import com.sungrow.common.constant.ErrCodeEnum;/** * @ author shihaifeng * @ date 2019-08-01 11:44 * @ desc (used to quickly return result sets) * * / public class JsonResult {public static ResultBaseEntity success () {return result (ErrCodeEnum.ERR_CODE_1.getErrCode (), null, ErrCodeEnum.ERR_CODE_1.getErrMsg ()) } public static ResultBaseEntity success (T data) {return result (ErrCodeEnum.ERR_CODE_1.getErrCode (), data, ErrCodeEnum.ERR_CODE_1.getErrMsg ());} public static ResultBaseEntity success (ErrCodeEnum iCode) {return result (iCode.getErrCode (), null, iCode.getErrMsg ());} public static ResultBaseEntity success (ErrCodeEnum iCode, Object data) {return result (iCode.getErrCode (), data, iCode.getErrMsg ()) } public static ResultBaseEntity error (ErrCodeEnum iCode) {return error (iCode, null);} public static ResultBaseEntity error (ErrCodeEnum iCode, T data) {return result (iCode.getErrCode (), data, iCode.getErrMsg ());} public static ResultBaseEntity error (ErrCodeEnum iCode, T data, String message) {return result (iCode.getErrCode (), data, message) } / * @ param code return code * @ param data * @ param message * @ return * / public static ResultBaseEntity result (String code, T data, String message) {ResultBaseEntity ResultBaseEntity = new ResultBaseEntity (); ResultBaseEntity.setResult_code (code); ResultBaseEntity.setResult_msg (message); if (data! = null) {ResultBaseEntity.setT (data) } return ResultBaseEntity;}}
5. Test interface
Import com.sungrow.common.api.RequestBaseParam;import com.sungrow.common.constant.ErrCodeEnum;import com.sungrow.modular.marchine.dto.MachineLargeAreaQueryDTO;import com.sungrow.modular.marchine.entity.MachineLargeArea;import com.sungrow.modular.marchine.service.IMachineLargeAreaService;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import lombok.extern.log4j.Log4j2;import org.sg.tools.response.APIResponse;import org.sg.tools.response.ResponseHandle;import org.sg.tools.util.CommTools Import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;/** *
* Theater table front-end controller *
* * @ author shiye * @ since 2019-07-26 * / @ Controller@RequestMapping ("/ marchine/machineLargeArea") @ Log4j2@Api (value = "Theater Management Interface") public class MachineLargeAreaController {@ Autowired private IMachineLargeAreaService machineLargeAreaService / * get all theater details * @ param baseParam * @ return APIResponse return encapsulated result set * * @ RequestBody plus json submission, not form submission * @ Validated must be added Otherwise, the parameters will not be verified * / @ ApiOperation (value= "get all theater details", notes= "get all theater details") @ PostMapping ("/ allList") @ ResponseBody public ResultBaseEntity allList (@ RequestBody @ Validated RequestBaseParam baseParam) {ResultBaseEntity resultBaseEntity = machineLargeAreaService.allList (baseParam); return resultBaseEntity }} at this point, I believe you have a deeper understanding of "Swagger2+springboot-mvc+hibernate-validator visual view plus parameter example analysis". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.