Swagger UI 与SpringMVC的整合
关于 Swagger
Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因:
- Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API。
- Swagger 可以生成客户端SDK代码用于各种不同的平台上的实现。
- Swagger 文件可以在许多不同的平台上从代码注释中自动生成。
- Swagger 有一个强大的社区,里面有许多强悍的贡献者。
Swagger 文档提供了一个方法,使我们可以用指定的 JSON 或者 YAML 摘要来描述你的 API,包括了比如 names、order 等 API 信息。
你可以通过一个文本编辑器来编辑 Swagger 文件,或者你也可以从你的代码注释中自动生成。各种工具都可以使用 Swagger 文件来生成互动的 API 文档。
Swagger 、SwaggerUI与SpringMVC的整合
1.Maven引入
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-staticdocs</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
2.配置webconfig.xml
将 DispatcherServlet 的 url-pattern 改为 /
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.在spring-mvc.xml中添加自动扫描
<mvc:annotation-driven /> <!-- 自动扫描(自动注入) -->
<context:component-scan base-package="com.xhl.swagger.api"/>
<mvc:default-servlet-handler/>
4.新建Swagger配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.google.common.base.Predicates; import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter { @Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
.build();
} @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/");
}
}
5.建测试的Controller和常量
public interface Constants {
/****** 系统标识符 开始 *********/
/**
* 错误 描述
*/
String MSG_ERROR = "error";
/**
* 成功 描述
*/
String MSG_SUCCESS = "OK"; /****** 系统状态码 开始 ******/
/**
* 请求失败
*/
int ERROR = 100;
/**
* 请求成功
*/
int SUCCESS = 200;
}
import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; @ApiModel
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable { private static final long serialVersionUID = 1L; /** 正常状态为0或200 **/
@ApiModelProperty(value = "状态代码", name = "状态代码")
private int code; /** 是code异常时,返回的错误信息(app直接显示) **/
@ApiModelProperty(value = "错误码描述", name = "错误码描述")
private String message; /** 返回的数据对象 **/
@ApiModelProperty(value = "数据对象", name = "数据对象")
private T data; /** 是code正常时的提示(不为空,app直接展示) **/
@ApiModelProperty(value = "code正常时的提示信息", name = "code正常时的提示信息")
private String toast = ""; /** response中允许 空值,不允许 NULL值出现 **/
@ApiModelProperty(value = "响应流信息", name = "响应流信息")
private String response = ""; public Result() {
} public Result(int code,String message) {
this.code = code;
this.message = message;
} public Result(int code,String message,T data) {
this.code = code;
this.message = message;
this.data = data;
} public Result(int code,String message,T data,String toast,String response) {
this.code = code;
this.message = message;
this.data = data;
this.toast = toast;
this.response = response;
} public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public T getData() {
return data;
} public void setData(T data) {
this.data = data;
} public String getToast() {
return toast;
} public void setToast(String toast) {
this.toast = toast;
} public String getResponse() {
return response;
} public void setResponse(String response) {
this.response = response;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data + '\'' +
", toast=" + toast + '\'' +
", response=" + response +
'}';
}
}
@ApiModel(value = "用户信息")
public class UserVo {
@ApiModelProperty(value = "用户id", required = true)
private String userId;
@ApiModelProperty(value = "昵称", required = true)
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
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.RestController; import com.qdingnet.pcloud.api.common.utils.StringUtils;
import com.qdingnet.pcloud.api.swagger.constants.Constants;
import com.qdingnet.pcloud.api.swagger.constants.Result;
import com.qdingnet.pcloud.api.swagger.vo.UserVo; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; @RestController
@RequestMapping("/api/json/user")
public class SwaggerController { @RequestMapping(value = "/add", method = RequestMethod.POST)
@ApiOperation(value = "添加用户", notes = "增加用户")
public Result<UserVo> add(@ApiParam(name = "token", value = "token",required = true) @RequestParam(name = "token", required = true) String token,
@ApiParam(name = "userName",value = "用户昵称",required = true)@RequestParam(name = "userName",required = true)String userName,
@ApiParam(name = "mobile",value = "手机",required = true)@RequestParam(name = "mobile",required = true)String mobile,
@ApiParam(required = true, name = "email", value = "邮箱") @RequestParam(name = "email", required = true) String email ) {
UserVo userVo = new UserVo();
userVo.setUserId(StringUtils.getUUID());
userVo.setUserName(userName);
return new Result<UserVo>(Constants.SUCCESS,Constants.MSG_SUCCESS,userVo);
} @RequestMapping(value = "/getUser", method = RequestMethod.GET)
@ApiOperation(value = "测试获取用户", notes = "测试获取用户")
public Result<UserVo> getUser() {
UserVo userVo = new UserVo();
userVo.setUserId(StringUtils.getUUID());
userVo.setUserName("测试获取用户");
return new Result<UserVo>(Constants.SUCCESS,Constants.MSG_SUCCESS,userVo);
}
}
6.测试运行
首先通过:http://localhost:8080/工程名/api/json/user/getUser.do 可以访问:
{"code":200,"message":"OK","data":{"userId":"d1239dc4e4164662af754c64e42762cd","userName":"测试获取用户"},"toast":"","response":""}
其次通过:http://localhost:8080/工程名/v2/api-docs 可以查看具体的接口描述信息:
最后通过:http://localhost:8080/工程名/swagger-ui.html 进行访问和测试:
7.如果请求需要带参数的话,Swagger可以直接显示出可以输入请求参数的入口和描述:
请求结果:
Try it out
Swagger UI 与SpringMVC的整合的更多相关文章
- Swagger UI 与SpringMVC的整合 II
pom.xml <!-- swagger开始 --> <dependency> <groupId>io.springfox</groupId> < ...
- WebApi使用swagger ui自动生成接口文档
之前就写到.最近正在使用webapi.这里介绍一个实用的东西swageer ui现在开发都是前后端分开.我们这里是给前端提供api.有时候对于一个api的描述,并不想专门写一份文档.很浪费时间.swa ...
- SpringMVC+JWT+Swagger UI+RestFul
前言: 其实很早就想写这篇文章了,因为我觉得这会对很多新手有指引作用,当初自己也是瞎子过河的摸索着过来的.目前后台开发比较流行的MVC框架中使用Spring MVC还是比较多的,当然还有Spring ...
- Swagger与SpringMVC项目整合
Swagger与SpringMVC项目整合 来源:http://www.2cto.com/kf/201502/376959.html 为了方便的管理项目中API接口,在网上找了好多关于API接口管理的 ...
- TP框架整合Swagger UI接口文档
1.下载swagger ui:http://swagger.io/swagger-ui/: 2.在应用目录里新建一个目录xxx:如图 3.解压后把dist目录的所有文件拷贝到新建的目录里面: 4.在新 ...
- SpringMVC融合Swagger UI使用
相信大家都很熟悉springmvc,在用其进行开发工作的时候,有没有遇到几个小问题?比如: 1.前后端分离的模式下,前端开发人员如何得知后端的开发进度,有哪些接口可用? 2.后端开发人员在测试自己的接 ...
- 使用 Swagger UI 与 Swashbuckle 创建 RESTful Web API 帮助文件
作者:Sreekanth Mothukuru 2016年2月18日 本文旨在介绍如何使用常用的 Swagger 和 Swashbuckle 框架创建描述 Restful API 的交互界面,并为 AP ...
- sonne_game网站开发03 spring-mvc+freemarker整合
今天的任务就是在spring+mybatis+springmvc的基础上,将freemarker整合进来. freemarker是什么? freemarker是一种模板引擎.它的目的是基于模板和数据, ...
- IDEA下使用maven构建web项目(SpringMVC+Mybatis整合)
需求背景:由于最近总是接到一些需求,需要配合前端团队快速建设移动端UI应用或web应用及后台业务逻辑支撑的需求,若每次都复用之前复杂业务应用的项目代码,总会携带很多暂时不会用到的功能或组件,这样的初始 ...
随机推荐
- SpringMVC的请求处理流程
- 数据结构 BM算法
BM算法是比KMP算法更快的字符串模式匹配算法.BM算法最好情况下的时间复杂度是O(n),KMP算法最好情况下的时间复杂度是O(n+m),两者最坏情况下的时间复杂度均是O(m*n).其中,n指目标串长 ...
- 深入理解JVM(9)——类加载的过程
加载是类加载的第一步. 一.加载 a)加载的过程 1)通过一个类的全限定名获取这个类的二进制字节流,也就是class文件 2)将二进制字节流的存储结构转换为特定的数据结构,存储在方法区 3)在内存中创 ...
- 【LCA&倍增】货物运输 @upcexam5909
时间限制: 1 Sec 内存限制: 128 MB 题目描述 在一片苍茫的大海上,有n座岛屿,岛屿与岛屿之间由桥梁连接,所有的岛屿刚好被桥梁连接成一个树形结构,即共n-1架桥梁,且从任何一座岛屿出发都能 ...
- 2018年东北农业大学春季校赛 I-wyh的物品(二分查找)
链接:https://www.nowcoder.com/acm/contest/93/I来源:牛客网 题目描述 wyh学长现在手里有n个物品,这n个物品的重量和价值都告诉你,然后现在让你从中选取k个, ...
- Vue 2.3、2.4 知识点小结
2.3 style 多重值: <div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }">< ...
- Creating a NuGet Package in 7 easy steps - Plus using NuGet to integrate ASP.NET MVC 3 into existing Web Forms applications
UPDATE: Check out my follow up post where I remove the need for editing the Global.asax.cs and show ...
- ARMv8学习 —— SP_EL0和SP_ELx
在AArch64状态下,SP对应的物理寄存器有如下四个(某一时刻只能对应下面其中一个): SP_EL0和SP_EL1 SP_EL2 SP_EL3 如何使用呢? 1.如果程序运行在EL0,那么使用的是S ...
- u-boot-2018-09 分析 v1
下载地址: https://pan.baidu.com/s/1YcQ1XpFyzmNcr1afw1RhgQ 或者:
- Arcmap内容列表刷新
Arcmap内容列表刷新ILayer pLayer = pFDOGLayer as ILayer; if (!pLayer.Visible) ...