zoukankan      html  css  js  c++  java
  • java集成swagger

    概览:

    • java集成Swagger
    • Swagger-UI的使用
    • Springboot跨域请求的访问解决

    Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。本文主要介绍了在 Spring Boot 添加 Swagger 支持, 生成可自动维护的 API 文档。

    1 . POM文件概览:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
    	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    
        <!--freemaker支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    
        <!--添加swagger支持-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
    
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.13</version>
        </dependency>
    </dependencies>
    

    2 . 在Application同目录下创建Swagger2的配置文件 Swagger2.java

    @Configuration
    @EnableSwagger2
    public class Swagger2 {
    
        @Bean
        public Docket config() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .useDefaultResponseMessages(false)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.yl.swagger.controller"))
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("这个标题")
                    .contact(new Contact("yl", "47.95.196.183/esileme", "280885685@qq.com"))
                    .build();
        }
    }
    

    .apis(RequestHandlerSelectors.basePackage("com.pxx.xxx.controller")) 指定了 Swagger 的扫描包名, 假如不指定此项, 在 Spring Boot 项目中, 会生成 base-err-controller 的 api 接口项。

    配置好swagger后,在项目中访问 ip:prot/v2/api-docs 即可访问生成文档的json结构,如(http://localhost:8080/v2/api-docs)可以看到,会出现一大串Json字符串。

    具体可参考Swagger官方示例

    3 . Swagger-UI配置

    Swagger扫描解析得到的是一个json文档,对于用户不太友好。下面介绍swagger-ui,它能够友好的展示解析得到的接口说明内容。

    github 上获取其所有的 dist 目录下东西放到需要集成的项目里,本文放入 resource/static/swagger 目录下。

    修改swagger/index.html文件,默认是从连接http://petstore.swagger.io/v2/swagger.json获取 API 的 JSON,这里需要将url值修改为http://{ip}:{port}/{projectName}/api-docs的形式,{}中的值根据自身情况填写,其实也就是步骤二中的json地址,我的是http://localhost:8080/v2/api-docs。

    因为swagger-ui项目都是静态资源,restful形式的拦截方法会将静态资源进行拦截处理,所以要对springboot进行静态资源拦截的处理。

    下一步,在代码中调用dist目录下的index.html文件,即可访问到接口文档说明了。

    4 . springboot添加freemaker模板引擎

    在默认的templates文件夹中新建welcome.ftl 内容如下:

    	    <!DOCTYPE html>
    	    <html>
    	    	<body>
    	    		Hello,${name}.欢迎阅读《${bookTitle}》
    	    	</body>
    	    </html>
    

    创建一个controller hellocontroller

    	@Controller
    	@RequestMapping("/test")
    	public class HelloController {
    	
    	
    	    @RequestMapping("")
    	    public Object test(ModelMap map) {
    	
    	        System.err.println("cnm");
    	
    	        map.put("name", "yl");
    	        map.put("bookTitle", "bookTitle");
    	
    	        return "welcome";
    	    }
    	}
    

    打开浏览器,访问http://localhost:8080/test 即可访问welcome页面。

    • 在访问index.html的时候,会提示跨域请求没有权限的问题,在Application中添加

        @Bean
        public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
        }
        
        private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
        }
      

    即可。

    备忘:

    • Swagger-UI本质上是一个写好的html静态页面,我们只需要将我们提供的接口写入index.html中,会给我们的接口数据渲染成一个html页面。
    • Swagger-UI会查找出所有写的请求地址,并显示出来,如我们定义了一个/test 接口,它会把这个接口给显示出来。
  • 相关阅读:
    Webstorm常用快捷键
    微信内置浏览器是什么?(复制篇)
    jquery.cookie.js 操作cookie实现记住密码功能的实现代码
    sublime text 3 快捷键大全
    http_load的安装及使用方法
    Mysql压测工具mysqlslap 讲解
    ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
    percona-toolkit工具包的使用教程之开发类工具
    MYSQL管理之主从同步管理
    percona-toolkit系列之介绍和安装(mysql复制工具)
  • 原文地址:https://www.cnblogs.com/esileme/p/7704063.html
Copyright © 2011-2022 走看看