springmvc 整合 swagger 自动生成 web api 文档

前提条件: 已引入spring以及spring mvc的包,并做好了相关配置,能够正常运行

一. pom中引入swagger相关的依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.5.0</version>
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.9</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-staticdocs</artifactId>
    <version>2.5.0</version>
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
        </exclusion>
        <exclusion>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </exclusion>
    </exclusions>
</dependency>             

二. web.xml中启用web容器的default servlet,将静态资源交由web容器处理(这里主要指html文件)

<!-- 让容器来处理静态文件,防止spring mvc去处理(spring mvc处理静态文件的能力不如容器本身) -->
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.wof</url-pattern>
</servlet-mapping>

四. 创建ApplicationSwaggerConfig类

package apidoc;

import org.springframework.context.annotation.Bean;

import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 
 * @author pan
 *
 */
@EnableSwagger2
public class ApplicationSwaggerConfig {

    @Bean
    public Docket addUserDocket() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        Contact contact = new Contact("潘志勇", "", "zhiyong.pan@comix.com.cn");
        ApiInfo apiInfo = new ApiInfo("进销存管理系统", "WEB API文档", "V0.0.1", "", contact, "", "");
        docket.apiInfo(apiInfo);
        return docket;
    }
}

三.spring mvc配置文件中加入如下配置

<!-- Include a swagger configuration -->
    <bean name="applicationSwaggerConfig" class="apidoc.ApplicationSwaggerConfig" />
    <mvc:default-servlet-handler/>

四. API编写测试

package com.qc.invoicing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Controller
@RequestMapping(value = "/test", produces = { "application/json;charset=utf-8" })
@Api(value = "/test", description = "测试Contrler")
public class TestController {

    @RequestMapping(value = "/restStyle/{id}", method = RequestMethod.GET)
    @ApiOperation(notes = "/restStyle", httpMethod = "GET", value = "rest风格方法")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "正常操作", response = StringAPIResponse.class) })
    @ResponseBody
    public StringAPIResponse restStyle(@ApiParam(required = true, value = "主键") @PathVariable(value = "id") long id) {
        System.err.println(id);
        StringAPIResponse apiResponse = new StringAPIResponse();
        apiResponse.setMsg("操作成功");
        apiResponse.setData("你好");
        return apiResponse;
    }

    @RequestMapping(value = "/getStyle", method = RequestMethod.GET)
    @ApiOperation(notes = "/getStyle", httpMethod = "GET", value = "get风格方法")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "正常操作", response = StringAPIResponse.class) })
    @ResponseBody
    public StringAPIResponse getStyle(@ApiParam(required = true, value = "主键") @RequestParam("id") long id) {
        System.err.println(id);
        StringAPIResponse apiResponse = new StringAPIResponse();
        apiResponse.setMsg("操作成功");
        apiResponse.setData("你好");
        return apiResponse;
    }

    @RequestMapping(value = "/postStyle", method = RequestMethod.POST)
    @ApiOperation(notes = "/postStyle", httpMethod = "POST", value = "post风格方法")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "正常操作", response = StringAPIResponse.class) })
    @ResponseBody
    public StringAPIResponse postStyle(@ApiParam(required = true, value = "简单数据") @RequestBody SimpleData data) {
        System.err.println(data.getName());
        StringAPIResponse apiResponse = new StringAPIResponse();
        apiResponse.setMsg("操作成功");
        apiResponse.setData("你好");
        return apiResponse;
    }

    @RequestMapping(value = "/traditionStyle", method = RequestMethod.GET, produces = { "application/xml;charset=utf-8" })
    @ApiOperation(notes = "转入页面:/WEB-INF/jsp/test.jsp", httpMethod = "GET", value = "传统风格方法")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "正常操作", response = StringAPIResponse.class) })
    public String traditionStyle() {
        return "/test";
    }

}

class SimpleData {

    @ApiModelProperty(value = "主键", hidden = false)
    private long id;

    @ApiModelProperty(value = "名称", required = true)
    private String name;

    @ApiModelProperty(value = "年龄")
    private int age;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

abstract class APIResponse<T> {

    @ApiModelProperty(value = "操作是否成功")
    private boolean optSuc = true;

    @ApiModelProperty(value = "操作失败时的提示信息")
    private String msg;

    @ApiModelProperty(value = "返回结果")
    private T data;

    public boolean isOptSuc() {
        return optSuc;
    }

    public void setOptSuc(boolean optSuc) {
        this.optSuc = optSuc;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

class StringAPIResponse extends APIResponse<String> {

}

五. 启动jetty(如果是使用maven命令运行web项目,请使用jetty作为web容器,否则无法访问swagger)

mvn jetty:run

//访问地址:
http://ip:端口/项目名/swagger-ui.html#/
例如:
http://localhost:9080/test-project/swagger-ui.html

结果:

Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,678评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,494评论 18 139
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 1,635评论 0 3
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,137评论 11 349
  • 一生中 我们要经历许多事情 要相识相交许多人 而心灵像一个筛子 在世事颠沛流离中 慢慢的一些人就漏掉了 不过对于智...
    一米阳光HUIWEI阅读 453评论 0 51