swagger-ui

如何使用swaggerui:

1. 创建maven项目:

 

 

2. 引入springMVC

 

修改web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 

 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 

 id="WebApp_ID" 

 version="3.1">

 

  <display-name>Archetype Created Web Application</display-name>

   <servlet>

    <servlet-name>MySpringMVCName</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:MySpringMVCName-servlet.xml</param-value> 

</init-param>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>MySpringMVCName</servlet-name>

    <url-pattern>/</url-pattern>

  </servlet-mapping>

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

  <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:applicationContext.xml</param-value>

  </context-param>

</web-app>

 

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.harvetech</groupId>

  <artifactId>maven-swagger-ui</artifactId>

  <packaging>war</packaging>

  <version>0.0.1-SNAPSHOT</version>

  <name>maven-swagger-ui Maven Webapp</name>

  <url>http://maven.apache.org</url>

  <properties>

 <springfox.version>2.7.0</springfox.version>

 <spring.boot.version>1.5.6.RELEASE</spring.boot.version>

  </properties>

 

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

    

    <!-- spring-web -->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

        <version>${spring.boot.version}</version>

    </dependency>

  </dependencies>

  <build>

    <finalName>maven-swagger-ui</finalName>

    <plugins>  

      <plugin>  

        <groupId>org.apache.maven.plugins</groupId>  

        <artifactId>maven-compiler-plugin</artifactId>  

        <configuration>  

          <source>1.7</source>  

          <target>1.7</target>  

        </configuration>  

      </plugin>  

    </plugins>  

  </build>

</project>

 

3. 添加接口:

 

 

4. 测试接口:

 

 

5. 集成swagger

 1) 引包

  <properties>

 <springfox.version>2.7.0</springfox.version>

  </properties>

<!-- swagger2核心依赖 -->

    <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger2</artifactId>

        <version>${springfox.version}</version>

    </dependency>

    <!-- swagger-ui为项目提供api展示及测试的界面 -->

    <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger-ui</artifactId>

        <version>${springfox.version}</version>

    </dependency>

引完包可以看到多了许多包,其中一个就是springfox-swagger-ui,其结构如下:

 

 

2) 添加SwaggerConfig

可以先加一个空内容的config类,只需要两个注解:

@Configuration

@EnableSwagger2

public class SwaggerConfig {

}

后面再来完善它。

 

3) 配置swagger-ui.html

我们希望通过访问

http://localhost:8080/maven-swagger-ui/swagger-ui.html

查看接口。

而此html

springfox-swagger-ui-2.7.0.jar下的页面,因此需要配置。

有两种方式:

1.添加配置类:

package com.harvetech.utils;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration

@EnableWebMvc

public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Override 

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

}

 

2.springMVC配置文件中配置

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />

<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />

两种方式效果一样。

 

4) 访问swagger-ui.html

 

可以看到,可以直接访问此页面了

  

5) Api注解

 package com.harvetech.controller;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiImplicitParam;

import io.swagger.annotations.ApiImplicitParams;

import io.swagger.annotations.ApiOperation;

import org.springframework.http.MediaType;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

@Controller

@Api(description = "登录/注销接口",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

public class UserController {

@RequestMapping(value = "/users", method = RequestMethod.GET)

@ResponseBody

    @ApiOperation(value = "获取用户接口")

//Valid values are {@code path}, {@code query}, {@code body}, {@code header} or {@code form}

    @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户id",paramType = "query", required = true)})

public String getUser(String id){

String result = "name: " + "gary" + " id: " + id;

System.out.println(result);

return result;

}

@RequestMapping(value = "/login", method = RequestMethod.POST)

@ResponseBody

    @ApiOperation(value = "登录接口")

    @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "登录名",paramType = "query", required = true),

            @ApiImplicitParam(name = "password", value = "登录密码",paramType = "query", required = true)})

public String login(String name, String password){

String result = "name: " + name + " password: " + password;

System.out.println(result);

return result;

}

}

 

可以看到输出结果:

 

· @Api:用在类上,说明该类的作用

· @ApiOperation:用在方法上,说明方法的作用

· @ApiImplicitParams:用在方法上包含一组参数说明

· @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

· paramType:参数放在哪个地方

· header-->请求参数的获取:@RequestHeader

· query-->请求参数的获取:@RequestParam

· path(用于restful接口)-->请求参数的获取:@PathVariable

· body(不常用)

· form(不常用)

· name:参数名

· dataType:参数类型

· required:参数是否必须传

· value:参数的意思

· defaultValue:参数的默认值

· @ApiResponses:用于表示一组响应

· @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

· code:数字,例如400

· message:信息,例如"请求参数没填好"

· response:抛出异常的类

· @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)

· @ApiModelProperty:描述一个model的属性

 

 

6) 完善SwaggerConfig

package com.harvetech.utils;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.ParameterBuilder;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.schema.ModelRef;

import springfox.documentation.service.ApiInfo;

import springfox.documentation.service.Contact;

import springfox.documentation.service.Parameter;

import springfox.documentation.spi.DocumentationType;

import springfox.documentation.spring.web.plugins.Docket;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

import java.util.List;

@Configuration

@EnableSwagger2

public class SwaggerConfig {

    @Bean

    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(apiInfo())

                .useDefaultResponseMessages(false)

                .globalOperationParameters(globalOperationParameters())// 全局参数

                .select()

                .apis(RequestHandlerSelectors.any())

                .paths(PathSelectors.regex("/.*"))// 监控所有路径

                .build();

    }

    private List<Parameter> globalOperationParameters(){

        ParameterBuilder builder = new ParameterBuilder();

        Parameter parameter = builder.name("token").description("登录接口返回的token")

                .modelRef(new ModelRef("string"))

                .parameterType("header")

                .required(false).build();

        ArrayList<Parameter> parameters = new ArrayList<>();

        parameters.add(parameter);

        return parameters;

    }

    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()

                .title("测试API文档")

                .description("北京合源智慧科技发展有限公司 Copyright 2015-2023 (C) All Rights Reserved.")

                .termsOfServiceUrl("http://www.harvetech.cn/")

                .contact(new Contact("gary",null,"callmegary@163.com"))

                .version("1.0")

                .build();

    }

}

 

其中apiInfo中配置一些页面展示信息,如文档名称、说明、联系人、邮箱、版本号等

 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值