替换jhSpring-boot-core pom文件原swagger依赖,如下

  <!--swagger3-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
            <version>${knife4j.version}</version>
        </dependency>

替换jhSpring-boot pom文件properties标签中swagger版本定义,如下

 <knife4j.version>4.1.0</knife4j.version>

一、跨域配置,请求拦截配置

@Configuration
public class GlobalWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	//自定义全局拦截配置
        registry.addInterceptor(new GlobalHandlerInterceptor())
                .excludePathPatterns("/swagger-resources/**")
                .excludePathPatterns("doc.html")
                .excludePathPatterns("/swagger/**")
                .excludePathPatterns("swagger-ui.html");
    }
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        //是否允许请求带有验证信息
        corsConfiguration.setAllowCredentials(true);
        // 允许访问的客户端域名
        corsConfiguration.addAllowedOriginPattern("*");
        // 允许服务端访问的客户端请求头
        corsConfiguration.addAllowedHeader("*");
        // 允许访问的方法名,GET POST等
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

二、统一返回常量定义

public interface RCodeConstant {
    //成功
    Integer SUCCESS = 200;
    //失败
    Integer ERROR = 500;
    //未认证
    Integer UNAUTHORIZED = 401;
    //禁止访问
    Integer FORBIDDEN = 403;
    //失败
    Integer FAIL = -1;

}

public enum RCodeEnum {
    FAIL(-1,"请求超时"),
    SUCCESS(200,"请求成功"),
    ERROR(500,"服务器请求失败"),
    FORBIDDEN(403,"禁止访问"),
    UNAUTHORIZED(401,"用户未登录");
    private Integer code;
    private String msg;

    RCodeEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public String getMsg(int code){
        for (RCodeEnum value : RCodeEnum.values()) {
            if (value.code == code) {
                return value.msg;
            }
        }
        return "访问未知错误!";
    }
}

三、统一返回实体类

@Data
public class ResponseData<T> {
    
    private Integer code;

    private String msg;

    private T data;


    //成功接口返回
    public static <T> ResponseData<T> sucess(){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setCode(RCodeConstant.SUCCESS);
        responseData.setMsg(RCodeEnum.getMsg(RCodeConstant.SUCCESS));
        return responseData;
    }

    //成功接口返回
    public static <T> ResponseData<T> sucess(T data){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setCode(RCodeConstant.SUCCESS);
        responseData.setMsg(RCodeEnum.getMsg(RCodeConstant.SUCCESS));
        responseData.setData(data);
        return responseData;
    }

    //失败返回
    public static <T> ResponseData<T> error(){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setCode(RCodeConstant.FAIL);
        responseData.setMsg(RCodeEnum.getMsg(RCodeConstant.FAIL));
        return responseData;
    }

    //服务器错误返回
    public static <T> ResponseData<T> error(String msg){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setCode(RCodeConstant.ERROR);
        responseData.setMsg(msg);
        return responseData;
    }

    //接口错误返回
    public static <T> ResponseData<T> error(Integer code, String msg){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setCode(code);
        responseData.setMsg(msg);
        return responseData;
    }

    //禁止访问
    public static <T> ResponseData<T> Forbidden(){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setCode(RCodeConstant.FORBIDDEN);
        responseData.setMsg(RCodeEnum.getMsg(RCodeConstant.FORBIDDEN));
        return responseData;
    }

    //未认证
    public static <T> ResponseData<T> authError(){
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setCode(RCodeConstant.UNAUTHORIZED);
        responseData.setMsg(RCodeEnum.getMsg(RCodeConstant.UNAUTHORIZED));
        return responseData;
    }

四、satoken全局拦截策略(未写登录,后续完善)

public class GlobalHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//      获取进过拦截器的路径
        String requestURI = request.getRequestURI();

        return true;
    }

    /**
     * 目标方法执行完成以后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 页面渲染以后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}

五、全局异常配置

public class GlobalException  extends RuntimeException {
    private int code;
    private String msg;


    public GlobalException(int code) {
        this.code = code;
        this.msg = RCodeEnum.ERROR.getMsg(code);
    }

    public GlobalException(String msg){
        super(msg);
        this.code = RCodeConstant.ERROR;
        this.msg = msg;
    }
}

六、swagger配置

@Configuration
public class SwaggerConfig {

	//swagger 访问地址http://ip:port/doc.html#/home
    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("惊鸿-swagger")
                        .contact(new Contact().name("SongTiankai").email("908880267@qq.com").url("https://bbs.csdn.net/forums/JHUNITY"))
                        .description("惊鸿API文档")
                        .version("v1")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("外部文档")
                        .url("https://springshop.wiki.github.org/docs"));
    }
}

七、测试DEMO

@RestController
@RequestMapping("demo")
public class DemoController {
    
    @GetMapping("getTest")
    public ResponseData getTest(){
        return ResponseData.sucess("ok");
    }
}

swagger页面

从零开始,手撸一套基础框架(第二章 配置集成)-LMLPHP

接口测试

从零开始,手撸一套基础框架(第二章 配置集成)-LMLPHP

04-29 23:16