前言
最近工作需要,需要将Swagger整合到项目里面去,因为这些历史项目都是使用j基于servlet的框架,所以需要开始研究一下Swagger整合Servlet。作为一个面向搜索引擎编程的人,第一件事就是网上找资料,结果谷歌百度都翻遍了,就一篇文章相关,但是里面的内容参考价值不大,于是就有了这篇博客。本文仅作记录,当然能帮到需要人就更好了。
资源下载
本文示例:https://download.csdn.net/download/yunzaiqintian/11987694
准备
创建一个基于maven的web项目,怎么创建省略,网上资料很多,或者直接下载本文的示例
步骤
1.添加依赖项
pom.xml里面的内容如下:
<!--示例里面的依赖,部分jar可能不需要,暂时没移除 -->
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-servlet</artifactId>
<version>${swagger-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api-version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
</dependencies>
<properties>
<swagger-version>1.5.22-SNAPSHOT</swagger-version>
<servlet-api-version>2.5</servlet-api-version>
<jackson-version>2.9.10</jackson-version>
<logback-version>1.0.1</logback-version>
<junit-version>4.8.1</junit-version>
<commons-lang-version>3.2.1</commons-lang-version>
<slf4j-version>1.6.3</slf4j-version>
<coverage.line.minimum>0.90</coverage.line.minimum>
<testng-version>6.9.4</testng-version>
</properties>
2.修改web.xml
<!-- sample servlet -->
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>io.swagger.sample.servlet.SampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>/sample/users/*</url-pattern>
</servlet-mapping>
<!-- swagger servlet reader -->
<servlet>
<servlet-name>DefaultServletConfig</servlet-name>
<servlet-class>io.swagger.servlet.config.DefaultServletConfig</servlet-class>
<init-param>
<param-name>swagger.resource.package</param-name>
<param-value>io.swagger.sample.servlet</param-value>
</init-param>
<!--这里换成你项目的访问地址 http://localhost:8080/java-servlet-->
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8080/java-servlet</param-value>
</init-param>
<init-param>
<param-name>api.version</param-name>
<param-value>1.0.0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- swagger api declaration -->
<servlet>
<servlet-name>ApiDeclarationServlet</servlet-name>
<servlet-class>io.swagger.servlet.listing.ApiDeclarationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ApiDeclarationServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>io.swagger.sample.util.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.最后就是定义你的接口,比如此处的SampleServlet
package io.swagger.sample.servlet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Contact;
import io.swagger.annotations.Info;
import io.swagger.annotations.License;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import io.swagger.sample.model.SampleData;
import io.swagger.util.Json;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SwaggerDefinition(
info = @Info(
description = "This is a sample server",
version = "1.0.0",
title = "Swagger Sample Servlet",
termsOfService = "http://swagger.io/terms/",
contact = @Contact(name = "Sponge-Bob", email = "apiteam@swagger.io", url = "http://swagger.io"),
license = @License(name = "Apache 2.0", url = "http://www.apache.org/licenses/LICENSE-2.0.html")
),
consumes = {"application/json", "application/xml"},
produces = {"application/json", "application/xml"},
schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS},
tags = {@Tag(name = "users", description = "Operations about user")}
)
@Api(value = "/sample/users", description = "gets some data from a servlet")
public class SampleServlet extends HttpServlet {
private static final long serialVersionUID = -4384169231342668110L;
@ApiOperation(httpMethod = "GET", value = "Resource to get a user", response = SampleData.class, nickname = "getUser")
@ApiResponses({@ApiResponse(code = 400, message = "Invalid input", response = io.swagger.sample.model.ApiResponse
.class)})
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "User ID", required = true, dataType = "integer", paramType =
"query"),
@ApiImplicitParam(name = "name", value = "User's name", required = true, dataType = "string", paramType =
"query"),
@ApiImplicitParam(name = "email", value = "User's email", required = true, dataType = "string", paramType
= "query"),
@ApiImplicitParam(name = "age", value = "User's age", required = true, dataType = "integer", paramType =
"query"),
@ApiImplicitParam(name = "dateOfBirth", value = "User's date of birth, in dd-MM-yyyy format",
dataType = "java.util.Date", paramType = "query")})
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String result;
try {
final Integer id = Integer.parseInt(request.getParameter("id"));
final String name = request.getParameter("name");
final String email = request.getParameter("email");
final Integer age = Integer.parseInt(request.getParameter("age"));
final Date dateOfBirth = new SimpleDateFormat("dd-MM-yyyy").parse(request.getParameter("dateOfBirth"));
result = Json.pretty(new SampleData(id, name, email, age, dateOfBirth));
} catch (Exception ex) {
result = Json.pretty(new io.swagger.sample.model.ApiResponse(400, ex.getMessage()));
}
response.getOutputStream().write(result.getBytes(StandardCharsets.UTF_8));
}
}
4.整合swagger-ui页面
下载swagger-ui,下载地址https://github.com/swagger-api/swagger-ui,将dist文件夹里面的内容拷贝到你的项目的webapp里,路径自己定义,比如此处
并且修改index.html 里面的内容
url为你本地的url,比如本文的http://localhost:8080/java-servlet/api/swagger.json
验证是否成功
至此,你的http://localhost:port/项目名称/api/swagger.json 已经有数据返回,如下所示:
访问http://localhost:8080/java-servlet/swagger/index.html (此处地址取决于项目名称以及存放dist内容路径) 也能看到如下内容