本篇內(nèi)容主要講解“Swagger2+springboot-mvc+hibernate-validator可視化視圖加參數(shù)舉例分析”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Swagger2+springboot-mvc+hibernate-validator可視化視圖加參數(shù)舉例分析”吧!
目前創(chuàng)新互聯(lián)已為1000多家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬主機(jī)、網(wǎng)站托管、服務(wù)器租用、企業(yè)網(wǎng)站設(shè)計(jì)、吉利網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
1 導(dǎo)入需要的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構(gòu)建api文檔") .description("簡(jiǎn)單優(yōu)雅的restfun風(fēng)格") .termsOfServiceUrl("xxx") .version("2.9.2") .build(); } }
3.封裝基本請(qǐng)求參數(shù)對(duì)象
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 請(qǐng)求頭的基礎(chǔ)參數(shù) **/ @ApiModel @Data public class RequestBaseParam<T>{ /** * 用戶定位區(qū)域編碼 */ /*@NotNull(message = "area不能為空") @Length(min = 6, max = 6, message = "area長(zhǎng)度為6") @ApiModelProperty(value = "用戶定位區(qū)域編碼") private String area;*/ /** * 提交的數(shù)據(jù)進(jìn)行base64簽名,針對(duì)敏感接口(支付)采用對(duì)稱加密算法進(jìn)行加密 */ /*@ApiModelProperty(value = "data") private String data;*/ /** * 客戶端根據(jù)一定規(guī)則生成的md5驗(yàn)證碼,以保證數(shù)據(jù)訪問的安全性; Sign值32位,不為空 */ // @NotNull(message = "sign不能為空") // @Length(min = 32, max = 32, message = "sign長(zhǎng)度為32") @ApiModelProperty(value = "sign") private String sign; /** * 時(shí)間戳:客戶端生成加密值時(shí)的時(shí)間戳;加一位設(shè)備類型 時(shí)間戳(13位)+設(shè)備類型(1位)共14位,不為空 */ // @NotNull(message = "tt不能位空") // @Length(min = 14, max = 14, message = "tt長(zhǎng)度為14") @ApiModelProperty(value = "時(shí)間戳") private String tt; /** * 登錄用戶ID, 可為空 */ @NotNull(message = "登錄用戶ID不能為空") @ApiModelProperty(value = "登錄用戶ID") private Integer uid; /** * 泛型:自定義請(qǐng)求參數(shù)實(shí)體對(duì)象 * 嵌套驗(yàn)證必須用 @Valid */ @Valid @NotNull(message = "自定義參數(shù)必傳") 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 用來處理參數(shù)綁定綁定異常的全局處理器 **/ @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 = "校驗(yàn)失敗: "; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMesssage += fieldError.getDefaultMessage() + ", "; } /** * 把錯(cuò)誤結(jié)果集封裝給客戶 */ resultBaseEntity.setResult_code("400"); resultBaseEntity.setResult_msg(errorMesssage); return resultBaseEntity; } /** * 攔擊json提交過來的參數(shù)綁定異常,返回給客戶端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校驗(yàn)失敗: "; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMesssage += fieldError.getDefaultMessage() + ", "; } resultBaseEntity.setResult_code("400"); resultBaseEntity.setResult_msg(errorMesssage); return resultBaseEntity; } }
4.增加返回對(duì)象封裝
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 (返回封裝結(jié)果集) **/ @ApiModel(value = "返回封裝結(jié)果集") @Data public class ResultBaseEntity<T> implements Serializable { @ApiModelProperty(value = "結(jié)果集編碼,1:成功") private String result_code ; @ApiModelProperty(value = "結(jié)果集消息") private String result_msg ; @ApiModelProperty(value = "返回類") private T t ; }
快速返回結(jié)果集工具
package com.sungrow.common.api; import com.sungrow.common.constant.ErrCodeEnum; /** * @author shihaifeng * @date 2019-08-01 11:44 * @desc (用來快速返回結(jié)果集) **/ 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.測(cè)試接口
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> * 大區(qū)表 前端控制器 * </p> * * @author shiye * @since 2019-07-26 */ @Controller @RequestMapping("/marchine/machineLargeArea") @Log4j2 @Api(value = "大區(qū)管理接口") public class MachineLargeAreaController { @Autowired private IMachineLargeAreaService machineLargeAreaService ; /** * 獲取所有大區(qū)詳細(xì)信息 * @param baseParam * @return APIResponse 返回封裝結(jié)果集 * * @RequestBody 加上是json提交,不加是表單提交 * @Validated 注解一定要加;不然不會(huì)對(duì)參數(shù)進(jìn)行校驗(yàn) */ @ApiOperation(value="獲取所有大區(qū)詳細(xì)信息", notes="獲取所有大區(qū)詳細(xì)信息") @PostMapping("/allList") @ResponseBody public ResultBaseEntity<List<MachineLargeArea>> allList(@RequestBody @Validated RequestBaseParam baseParam){ ResultBaseEntity<List<MachineLargeArea>> resultBaseEntity = machineLargeAreaService.allList(baseParam); return resultBaseEntity; } }
到此,相信大家對(duì)“Swagger2+springboot-mvc+hibernate-validator可視化視圖加參數(shù)舉例分析”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
分享文章:Swagger2+springboot-mvc+hibernate-validator可視化視圖加參數(shù)舉例分析
轉(zhuǎn)載來于:http://aaarwkj.com/article30/isjgpo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、電子商務(wù)、服務(wù)器托管、App設(shè)計(jì)、靜態(tài)網(wǎng)站、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)