千家信息网

Swagger2+springboot-mvc+hibernate-validator可视化视图加参数举例分析

发表于:2024-11-28 作者:千家信息网编辑
千家信息网最后更新 2024年11月28日,本篇内容主要讲解"Swagger2+springboot-mvc+hibernate-validator可视化视图加参数举例分析",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就
千家信息网最后更新 2024年11月28日Swagger2+springboot-mvc+hibernate-validator可视化视图加参数举例分析

本篇内容主要讲解"Swagger2+springboot-mvc+hibernate-validator可视化视图加参数举例分析",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Swagger2+springboot-mvc+hibernate-validator可视化视图加参数举例分析"吧!

1 导入需要的jar包

                    io.springfox            springfox-swagger2            2.9.2                            io.springfox            springfox-swagger-ui            2.9.2                            org.springframework.boot            spring-boot-starter-web        

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@EnableSwagger2public 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@Datapublic class RequestBaseParam{    /**     * 用户定位区域编码     */    /*@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 用来处理参数绑定绑定异常的全局处理器 **/@RestControllerAdvicepublic class BizExceptionHandler {    /**     * 接收 表单 提交过来的异常,返回给客户端json格式     *     * @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 = "校验失败: ";        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 myMethodArgumentNotValidException(MethodArgumentNotValidException e){        ResultBaseEntity 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 = "返回封装结果集")@Datapublic class ResultBaseEntity 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  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    返回码     * @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.测试接口

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;/** * 

* 大区表 前端控制器 *

* * @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> allList(@RequestBody @Validated RequestBaseParam baseParam){ ResultBaseEntity> resultBaseEntity = machineLargeAreaService.allList(baseParam); return resultBaseEntity; }}

到此,相信大家对"Swagger2+springboot-mvc+hibernate-validator可视化视图加参数举例分析"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0