您好,登錄后才能下訂單哦!
本篇內容主要講解“Swagger2+springboot-mvc+hibernate-validator可視化視圖加參數舉例分析”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Swagger2+springboot-mvc+hibernate-validator可視化視圖加參數舉例分析”吧!
1 導入需要的jar包
<!--swagger2的jar包--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- 其中依賴了 hibernate.validator --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2.整合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 @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.sungrow.modular.marchine.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("springboot利用swagger構建api文檔") .description("簡單優雅的restfun風格") .termsOfServiceUrl("xxx") .version("2.9.2") .build(); } }
3.封裝基本請求參數對象
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 * @desc 請求頭的基礎參數 **/ @ApiModel @Data public class RequestBaseParam<T>{ /** * 用戶定位區域編碼 */ /*@NotNull(message = "area不能為空") @Length(min = 6, max = 6, message = "area長度為6") @ApiModelProperty(value = "用戶定位區域編碼") private String area;*/ /** * 提交的數據進行base64簽名,針對敏感接口(支付)采用對稱加密算法進行加密 */ /*@ApiModelProperty(value = "data") private String data;*/ /** * 客戶端根據一定規則生成的md5驗證碼,以保證數據訪問的安全性; Sign值32位,不為空 */ // @NotNull(message = "sign不能為空") // @Length(min = 32, max = 32, message = "sign長度為32") @ApiModelProperty(value = "sign") private String sign; /** * 時間戳:客戶端生成加密值時的時間戳;加一位設備類型 時間戳(13位)+設備類型(1位)共14位,不為空 */ // @NotNull(message = "tt不能位空") // @Length(min = 14, max = 14, message = "tt長度為14") @ApiModelProperty(value = "時間戳") private String tt; /** * 登錄用戶ID, 可為空 */ @NotNull(message = "登錄用戶ID不能為空") @ApiModelProperty(value = "登錄用戶ID") private Integer uid; /** * 泛型:自定義請求參數實體對象 * 嵌套驗證必須用 @Valid */ @Valid @NotNull(message = "自定義參數必傳") 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.使用aop攔截異常
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 * @desc 用來處理參數綁定綁定異常的全局處理器 **/ @RestControllerAdvice public class BizExceptionHandler { /** * 接收 表單 提交過來的異常,返回給客戶端json格式 * * @param e * @return */ @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResultBaseEntity<Void> bindException(BindException e) { ResultBaseEntity<Void> resultBaseEntity = new ResultBaseEntity<>(); BindingResult bindingResult = e.getBindingResult(); String errorMesssage = "校驗失敗: "; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMesssage += fieldError.getDefaultMessage() + ", "; } /** * 把錯誤結果集封裝給客戶 */ resultBaseEntity.setResult_code("400"); resultBaseEntity.setResult_msg(errorMesssage); return resultBaseEntity; } /** * 攔擊json提交過來的參數綁定異常,返回給客戶端json格式 * @param e * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResultBaseEntity<Void> myMethodArgumentNotValidException(MethodArgumentNotValidException e){ ResultBaseEntity<Void> resultBaseEntity = new ResultBaseEntity<>(); BindingResult bindingResult = e.getBindingResult(); String errorMesssage = "josn校驗失敗: "; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMesssage += fieldError.getDefaultMessage() + ", "; } resultBaseEntity.setResult_code("400"); resultBaseEntity.setResult_msg(errorMesssage); return resultBaseEntity; } }
4.增加返回對象封裝
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 (返回封裝結果集) **/ @ApiModel(value = "返回封裝結果集") @Data public class ResultBaseEntity<T> implements Serializable { @ApiModelProperty(value = "結果集編碼,1:成功") private String result_code ; @ApiModelProperty(value = "結果集消息") private String result_msg ; @ApiModelProperty(value = "返回類") private T t ; }
快速返回結果集工具
package com.sungrow.common.api; import com.sungrow.common.constant.ErrCodeEnum; /** * @author shihaifeng * @date 2019-08-01 11:44 * @desc (用來快速返回結果集) **/ public class JsonResult { public static ResultBaseEntity success() { return result(ErrCodeEnum.ERR_CODE_1.getErrCode(), null, ErrCodeEnum.ERR_CODE_1.getErrMsg()); } public static <T> ResultBaseEntity<T> 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 <T> ResultBaseEntity<T> error(ErrCodeEnum iCode, T data) { return result(iCode.getErrCode(), data, iCode.getErrMsg()); } public static <T> ResultBaseEntity<T> error(ErrCodeEnum iCode, T data, String message) { return result(iCode.getErrCode(), data, message); } /** * @param code 返回碼 * @param data * @param message * @return */ public static <T> ResultBaseEntity<T> result(String code, T data, String message) { ResultBaseEntity<T> ResultBaseEntity = new ResultBaseEntity<T>(); ResultBaseEntity.setResult_code(code); ResultBaseEntity.setResult_msg(message); if (data != null) { ResultBaseEntity.setT(data); } return ResultBaseEntity; } }
5.測試接口
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; /** * <p> * 大區表 前端控制器 * </p> * * @author shiye * @since 2019-07-26 */ @Controller @RequestMapping("/marchine/machineLargeArea") @Log4j2 @Api(value = "大區管理接口") public class MachineLargeAreaController { @Autowired private IMachineLargeAreaService machineLargeAreaService ; /** * 獲取所有大區詳細信息 * @param baseParam * @return APIResponse 返回封裝結果集 * * @RequestBody 加上是json提交,不加是表單提交 * @Validated 注解一定要加;不然不會對參數進行校驗 */ @ApiOperation(value="獲取所有大區詳細信息", notes="獲取所有大區詳細信息") @PostMapping("/allList") @ResponseBody public ResultBaseEntity<List<MachineLargeArea>> allList(@RequestBody @Validated RequestBaseParam baseParam){ ResultBaseEntity<List<MachineLargeArea>> resultBaseEntity = machineLargeAreaService.allList(baseParam); return resultBaseEntity; } }
到此,相信大家對“Swagger2+springboot-mvc+hibernate-validator可視化視圖加參數舉例分析”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。