SpringBoot学习笔记之集成swagger,Swagger2在SpringBoot环境下的应用

2.1 Maven 配置

======属性配置=======

<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>

<asciidoctor.input.directory>${project.basedir}/docs/asciidoc</asciidoctor.input.directory>

<generated.asciidoc.directory>${project.build.directory}/asciidoc</generated.asciidoc.directory>

<asciidoctor.html.output.directory>${project.build.directory}/asciidoc/html</asciidoctor.html.output.directory>

<asciidoctor.pdf.output.directory>${project.build.directory}/asciidoc/pdf</asciidoctor.pdf.output.directory>

 

=====信任配置============

<!–离线文书档案–>

<dependency>

<groupId>org.springframework.restdocs</groupId>

<artifactId>spring-restdocs-mockmvc</artifactId>

<version>1.1.2.RELEASE</version>

<scope>test</scope>

</dependency>

<!–springfox-staticdocs 生成静态文书档案–>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-staticdocs</artifactId>

<version>2.6.1</version>

</dependency>

<!–swagger2 end–>

 

============插件配置==========

<!–通过Asciidoctor使得asciidoc生成别的的文书档案格式,比如:PDF
大概HTML5–>

<plugin>

<groupId>org.asciidoctor</groupId>

<artifactId>asciidoctor-maven-plugin</artifactId>

<version>1.5.3</version>

<!–生成PDF–>

<dependencies>

<dependency>

<groupId>org.asciidoctor</groupId>

<artifactId>asciidoctorj-pdf</artifactId>

<version>1.5.0-alpha.14</version>

</dependency>

<!– Comment this section to use the default jruby
artifact provided by the plugin –>

<dependency>

<groupId>org.jruby</groupId>

<artifactId>jruby-complete</artifactId>

<version>1.7.21</version>

</dependency>

</dependencies>

 

<!–文档生成配置–>

<configuration>

<sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>

<sourceDocumentName>index.adoc</sourceDocumentName>

<attributes>

<doctype>book</doctype>

<toc>left</toc>

<toclevels>3</toclevels>

<numbered></numbered>

<hardbreaks></hardbreaks>

<sectlinks></sectlinks>

<sectanchors></sectanchors>

<generated>${generated.asciidoc.directory}</generated>

</attributes>

</configuration>

<!–因为每一趟试行只能管理叁个后端,所以对于各样想要的出口类型,都以独自分开实行–>

<executions>

<!–html5–>

<execution>

<id>output-html</id>

<phase>test</phase>

<goals>

<goal>process-asciidoc</goal>

</goals>

<configuration>

<backend>html5</backend>

<outputDirectory>${asciidoctor.html.output.directory}</outputDirectory>

</configuration>

</execution>

<!–pdf–>

<execution>

<id>output-pdf</id>

<phase>test</phase>

<goals>

<goal>process-asciidoc</goal>

</goals>

<configuration>

<backend>pdf</backend>

<outputDirectory>${asciidoctor.pdf.output.directory}</outputDirectory>

</configuration>

</execution>

</executions>

</plugin>

 

 

@ApiImplicitParam(name =
“id”, value = “用户id”, required = true, paramType = “query”)

1.5 可选配置

在application.properties中出席以下配置,用于安装测量检验诉求的host,私下认可在swagger
ui上做哀求测量检验时都以以/users/1为路线发送央求。

借使急需改变央浼的根路线,就供给部署这些参数:

该Host也是swagger-ui发送测量检验乞求的Host,
平时大家会将将接口文书档案安排在测验服务器,那样就须求设置Host,

不然需要都是通过localhost发送,乞求不到测量试验服务器的接口。

springfox.documentation.swagger.v2.host
= yourapp.abc.com

布局获取api docs json数据的恳求路线 ,默以为/v2/api-docs:

springfox.documentation.swagger.v2.path = /api

 

int count = 0;

1. 集成Swagger

@DateTimeFormat(pattern = “yyyy-MM-dd
HH:mm:ss”)

1.2 配置类

package com.inn.demo.config;

 

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

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

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.service.ApiInfo;

import springfox.documentation.spi.DocumentationType;

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

import springfox.documentation.swagger2.annotations.EnableSwagger2;

 

@Configuration

@EnableSwagger2

public class SwaggerConfiguration extends WebMvcConfigurerAdapter {

//生产关闭swagger

@Value(“${swagger.enable}”)

private boolean enableSwagger;

 

// /**

// * 访谈swagger ui
出现404时可以把注释去掉试试

// * 消除能源系统财富目录与swagger
ui财富目录冲突难题

// *
这么些地点要双重注入一下财富文件,不然不会注入财富的,也不曾流入requestHandlerMappping,约等于xml配置的swagger能源配置

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

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

// * @param registry

// */

// @Override

// public void
addResourceHandlers(ResourceHandlerRegistry registry) {

//
registry.addResourceHandler(“/**”).addResourceLocations(“classpath:/static/”);

//
registry.addResourceHandler(“swagger-ui.html”)

//
.addResourceLocations(“classpath:/META-INF/resources/”);

// registry.addResourceHandler(“/webjars/**”)

//
.addResourceLocations(“classpath:/META-INF/resources/webjars/”);

// super.addResourceHandlers(registry);

// }

 

// /**

// * 协理分组 groupName

// */

// @Bean(value = “solrRestApi”)

// public Docket createSolrRestApi() {

// return new
Docket(DocumentationType.SWAGGER_2)

// .apiInfo(apiInfo()).groupName(“Solr
Demo模块”)

// .enable(enableSwagger)

// .select()

//
.apis(RequestHandlerSelectors.basePackage(“com.inn.demo.modules.solr.web”))

// .paths(PathSelectors.any())

// .build();

// }

 

@Bean(value = “userRestApi”)

public Docket createUserRestApi()
{

return new Docket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo())

//.groupName(“客商管理”)

.enable(enableSwagger)

.globalOperationParameters(createCommonParams())//公共参数

.select()

.apis(RequestHandlerSelectors.basePackage(“com.inn.demo.modules.user.web”))

.paths(PathSelectors.any())

.build();

}

 

private ApiInfo apiInfo()
{

return new ApiInfoBuilder()

.title(“Demo APIs”)

.description(“应用实例”)

//.termsOfServiceUrl(“;)

//.contact(new Contact(“开发者1”, “”,
xxx@163.com“))

.version(“1.0”)

.build();

}

/**
 * 创建公共参数
 * @return
 */
private List<Parameter> createCommonParams() {
    //添加head参数start
    List<Parameter> pars = new ArrayList<Parameter>();

    ParameterBuilder tokenPar = new ParameterBuilder();
    tokenPar.name("x-access-token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();

    pars.add(tokenPar.build());

    return pars;
    //添加head参数end
}

}

 

private Integer id;

3.1 增添自定义首页和译文

在resourece目录下创办META-INFresourece目录,然后创设多个称谓为”swagger-ui.html”
的HTML文件

图片 1

html内容:

<!DOCTYPE html>

<html>

<head>

<meta charset=”UTF-8″>

<title>Swagger UI</title>

<link rel=”icon” type=”image/png” href=”webjars/springfox-swagger-ui/images/favicon-32×32.png” sizes=”32×32″/>

<link rel=”icon” type=”image/png” href=”webjars/springfox-swagger-ui/images/favicon-16×16.png” sizes=”16×16″/>

<link href=’webjars/springfox-swagger-ui/css/typography.css’ media=’screen’ rel=’stylesheet’ type=’text/css’/>

<link href=’webjars/springfox-swagger-ui/css/reset.css’ media=’screen’ rel=’stylesheet’ type=’text/css’/>

<link href=’webjars/springfox-swagger-ui/css/screen.css’ media=’screen’ rel=’stylesheet’ type=’text/css’/>

<link href=’webjars/springfox-swagger-ui/css/reset.css’ media=’print’ rel=’stylesheet’ type=’text/css’/>

<link href=’webjars/springfox-swagger-ui/css/print.css’ media=’print’ rel=’stylesheet’ type=’text/css’/>

<script src=’webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/jquery.slideto.min.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/lodash.min.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/backbone-min.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/swagger-ui.min.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/jsoneditor.min.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/marked.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lib/swagger-oauth.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/springfox.js’ type=’text/javascript’></script> <!–国际化操作:选择中文版
–>

<script src=’webjars/springfox-swagger-ui/lang/translator.js’ type=’text/javascript’></script>

<script src=’webjars/springfox-swagger-ui/lang/zh-cn.js’ type=’text/javascript’></script>

</head>

<body class=”swagger-section”>

<div id=’header’>

<div class=”swagger-ui-wrap”>

<a id=”logo” href=”javascript:void(0)”>

<img class=”logo__img” alt=”swagger” height=”30″ width=”30″ src=”webjars/springfox-swagger-ui/images/logo_small.png” />

<span class=”logo__title”>在线API</span>

</a>

<form id=’api_selector’>

<div class=’input’>

<select id=”select_baseUrl” name=”select_baseUrl”></select>

</div>

<div class=’input’>

<input placeholder=”; id=”input_baseUrl” name=”baseUrl” type=”text”/>

</div>

<div id=’auth_container’></div>

<div class=’input’><a id=”explore” class=”header__btn” href=”#” data-sw-translate>Explore</a></div>

</form>

</div>

</div>

<div id=”message-bar” class=”swagger-ui-wrap” data-sw-translate></div>

<div id=”swagger-ui-container” class=”swagger-ui-wrap”></div>

</body>

</html>

马到成功大家访问 http://localhost:8080/swagger-ui.html 看看突显效果:

图片 2

@Configuration //
让Spring来加载该类配置

1.3 评释使用

效用范围

API

选用地方

对象属性

@ApiModelProperty

用在进出参数对象的字段上

说道集汇报

@Api

用于controller类上

共谋描述

@ApiOperation

用在controller的格局上

Response集

@ApiResponses

用在controller的法子上

Response

@ApiResponse

用在 @ApiResponses里边

非对象参数集

@ApiImplicitParams

用在controller的诀要上

非对象参数描述

@ApiImplicitParam

用在@ApiImplicitParams的不二秘籍里边

陈诉再次来到对象的意义

@ApiModel

用在回去对象类上

ApiImplicitParam的连带属性

属性

取值

作用

paramType

path

query

body

header

form

参数放在哪里:必须求有其一特性

header:header中提交:@RequestHeader获取

query :key=value提交:@RequestParam获取

path  :地址中付出:@PathVariable获取

body  :json流提交 :@RequestBody获取(限POST)

form  :表单提交:@RequestParam获取(限POST)

dataType

Long

String

参数的数据类型 只作为标记认证,并未实际验证

name

 

吸收参数名

value

 

收下参数的意思描述

required

 

参数是或不是必填

 

TRUE

必填

 

FALSE

非必填

defaultValue

 

默认值

ApiImplicitParam 与 ApiParam 的区别

ApiImplicitParam: 

  • 对Servlets只怕非 JAX-冠道S的条件,只好采取 ApiImplicitParam。
  • 在接纳上,ApiImplicitParam比ApiParam具备越来越少的代码侵入性,只要写在措施上就能够了,不过急需提供具体的属性技术合营swagger
    ui深入分析使用。
  • ApiParam只需求非常少的特性,与swagger ui合作越来越好。

 

代码实例:

@RestController

@RequestMapping(value = “/user”)

@Api(value = “/user”, description = “职员基本消息 “)

public class UserController
{

 

static Map<String, User> users = Collections.synchronizedMap(new HashMap<String,
User>());

 

@ApiOperation(value = “获取客户列表”, notes = “”)

@RequestMapping(value = {“/list”}, method = RequestMethod.GET)

public List<User>
getUserList() {

List<User> r = new ArrayList<User>(users.values());

return r;

}

 

@ApiOperation(value = “创立客户”, notes = “依据User对象创设顾客”)

@ApiImplicitParam(name = “user”, value = “顾客详细实体user”, required = true, dataType = “User”)

@RequestMapping(value = “add”, method = RequestMethod.POST)

public String postUser(@RequestBody User user)
{

users.put(user.getId(),
user);

return “success”;

}

 

@ApiOperation(value = “获取客户详细新闻”, notes = “根据url的id来获取顾客详细音讯”)

@ApiParam(name = “id”, value = “用户ID”, required = true)

@RequestMapping(value = “/get/{id}”, method = RequestMethod.GET)

public User getUser(@PathVariable(value = “id”) String id)
{

return users.get(id);

}

 

@ApiOperation(value = “更新顾客详细音信”, notes = “依照url的id来钦命更新指标,并依附传过来的user音信来更新顾客详细新闻”)

@RequestMapping(value = “/update/{id}”, method =
RequestMethod.PUT)

public String putUser(@PathVariable @ApiParam(name = “id”, value = “用户ID”, required = true) String
id,

@RequestBody @ApiParam(name = “user”, value = “客商详细实体user”, required = true) User user)
{

User u = users.get(id);

u.setName(user.getName());

u.setAge(user.getAge());

users.put(id, u);

return “success”;

}

 

@ApiOperation(value = “更新顾客名称和年龄”, notes = “更新顾客名称和年龄”)

@ApiImplicitParams({

@ApiImplicitParam(name = “id”, value = “用户ID”, required = true, dataType = “String”,paramType = “path”),

@ApiImplicitParam(name = “name”, value = “用户名”, required = true, dataType = “String”,paramType = “query”),

@ApiImplicitParam(name = “age”, value = “年龄”, required = true, dataType = “Integer”,paramType = “query”),

@ApiImplicitParam(name = “user”, value = “顾客消息”, required = true, dataType = “User”,paramType = “body”),

@ApiImplicitParam(name = “headerName”, value = “Header信息”, required = true, dataType = “String”,paramType = “header”)

})

@RequestMapping(value = “/update/info/{id}”, method =
RequestMethod.POST)

public String
updateUserNameAndAge(@PathVariable(value = “id”) String
id,

@RequestParam(value = “name”) String
name,

@RequestParam(value = “age”) Integer
age,

@RequestHeader(value = “headerName”) String
headerName,

@RequestBody User user)
{

User u = users.get(id);

u.setName(name);

u.setAge(age);

users.put(id, u);

return “success”;

}

 

@ApiOperation(value = “删除客户”, notes = “依照url的id来钦点删除对象”)

@ApiParam(name = “id”, value = “用户ID”, required = true)

@RequestMapping(value = “/delete/{id}”, method =
RequestMethod.DELETE)

public String deleteUser(@PathVariable String id)
{

users.remove(id);

return “success”;

}

 

@ApiOperation(value=”删除客商-传递数组”, notes=”删除对象,传递数组”)

@RequestMapping(value=”/users/deleteByIds”, method =
RequestMethod.DELETE)

public void deleteUsers(@ApiParam(“用户ID数组”) @RequestParam Integer[] ids)
{

for (int id:ids){

users.remove(id);

}

}

}

User实体类:

 

@JsonInclude(JsonInclude.Include.NON_NULL)

@JsonIgnoreProperties({“handler”, “hibernateLazyInitializer”})

@ApiModel(value = “User”)

public class User {

@ApiModelProperty(value = “ID”)

private String id;

 

@ApiModelProperty(value = “姓名”, required = true)

private String name;

 

@ApiModelProperty(value = “年龄”)

private Integer age;

 

public String getId()
{

return id;

}

 

public void setId(String id)
{

this.id = id;

}

 

public String getName()
{

return name;

}

 

public void setName(String name)
{

this.name = name;

}

 

public Integer getAge()
{

return age;

}

 

public void setAge(Integer age)
{

this.age = age;

}

}

 

<groupId>io.springfox</groupId>

3.2 更详尽的汉化

一经想进一步调动译文,能够在META-INFresourceswebjarsspringfox-swagger-uilang
目录下增加zh-cn.js文件.

图片 3

 

然后在译文(zh-cn.js )内容,如下

‘use strict’;

 

/* jshint quotmark: double */

window.SwaggerTranslator.learn({

“Warning: Deprecated”:”警告:已过时”,

“Implementation Notes”:”完结备注”,

“Response Class”:”响应类”,

“Status”:”状态”,

“Parameters”:”参数”,

“Parameter”:”参数”,

“Value”:”值”,

“Description”:”描述”,

“Parameter Type”:”参数类型”,

“Data Type”:”数据类型”,

“Response Messages”:”响应音讯”,

“HTTP Status Code”:”HTTP状态码”,

“Reason”:”原因”,

“Response Model”:”响应模型”,

“Request URL”:”请求URL”,

“Response Body”:”响应体”,

“Response Code”:”响应码”,

“Response Headers”:”响应头”,

“Hide Response”:”掩盖响应”,

“Headers”:”头”,

“Try it out!”:”试一下!”,

“Show/Hide”:”显示/隐藏”,

“List Operations”:”展现操作”,

“Expand Operations”:”张开操作”,

“Raw”:”原始”,

“can’t parse JSON. Raw result”:”不能深入分析JSON. 原始结果”,

“Example Value”:”示例”,

“Click to set as parameter value”:”点击设置参数”,

“Model Schema”:”模型架构”,

“Model”:”模型”,

“apply”:”应用”,

“Username”:”用户名”,

“Password”:”密码”,

“Terms of service”:”服务条约”,

“Created by”:”创建者”,

“See more at”:”查看更加多:”,

“Contact the developer”:”联系开拓者”,

“api version”:”api版本”,

“Response Content Type”:”响应Content Type”,

“Parameter content type:”:”参数类型:”,

“fetching resource”:”正在获得能源”,

“fetching resource list”:”正在赢得财富列表”,

“Explore”:”浏览”,

“Show Swagger Petstore Example Apis”:”显示 Swagger Petstore 示例 Apis”,

“Can’t read from server. It may not have the
appropriate access-control-origin settings.”:”不可能从服务器读取。恐怕未有科学设置access-control-origin。”,

“Please specify the protocol for”:”请钦赐左券:”,

“Can’t read swagger JSON from”:”不可能读取swagger JSON于”,

“Finished Loading Resource Information. Rendering
Swagger UI”:”已加载能源音信。正在渲染Swagger UI”,

“Unable to read api”:”不恐怕读取api”,

“from path”:”从路径”,

“server returned”:”服务器重回”

});

劳苦功高告成!

import
io.swagger.annotations.ApiModelProperty;

2.2 创建index.adoc文件

路径:项目名/docs/asciidoc/index.adoc

内容:

  1. include::{generated}/overview.adoc[]  
  2. include::{generated}/definitions.adoc[]  
  3. include::{generated}/paths.adoc[]  

 

/**

1.4 访谈调节台

 

按以下步骤配置,项目运维后拜谒:

</dependency>

2. 转换静态API文书档案pdf

return “error.jsp”;

2.3 创制生成pdf、html的测验类

package com.inn.demo;

 

import io.github.robwin.markup.builder.MarkupLanguage;

import io.github.robwin.swagger2markup.GroupBy;

import io.github.robwin.swagger2markup.Swagger2MarkupConverter;

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;

import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.http.MediaType;

import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import org.springframework.web.context.WebApplicationContext;

import springfox.documentation.staticdocs.SwaggerResultHandler;

 

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

 

@AutoConfigureMockMvc

@AutoConfigureRestDocs(outputDir
= “target/generated-snippets”)

@RunWith(SpringRunner.class)

@SpringBootTest

public class Swagger2MarkupTest
{

private String snippetDir = “target/generated-snippets”;

private String outputDir = “target/asciidoc”;

 

@Autowired

private WebApplicationContext context;

 

private MockMvc mockMvc;

 

@Before

public void setUp() {

this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();

}

 

/**

* 生成api html、pdf

* @throws Exception

*/

@Test

public void Test() throws Exception
{

// 得到swagger.json,写入outputDir目录中

mockMvc.perform(get(“/v2/api-docs”).accept(MediaType.APPLICATION_JSON))

.andDo(SwaggerResultHandler.outputDirectory(outputDir).build())

.andExpect(status().isOk())

.andReturn();

//
读取上一步生成的swagger.json转成asciiDoc,写入到outputDir

//
那几个outputDir必需和插件里面<generated></generated>标签配置一致

Swagger2MarkupConverter.from(outputDir + “/swagger.json”)

.withPathsGroupedBy(GroupBy.TAGS)//
按tag排序

.withMarkupLanguage(MarkupLanguage.ASCIIDOC)//
格式

.withExamples(snippetDir)

.build()

.intoFolder(outputDir);// 输出

}

}

 

运作测量试验类就可以生成pdf、html

  1. 生成的PDF和HTML文件:target/asciidoc/html and target/asciidoc/pdf
     

  2. Swagger-UI 汉化


@ApiImplicitParam(name =
“type”, value = “类型(修改:update;默认为查看)”, required = false,
paramType = “query”),

Swagger2在SpringBoot遭逢下的利用

//POST央求的法子不能平素转化到GET央求的办法,须要重定向

1.1 增多信任

<!–swagger2 start–>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.6.1</version>

</dependency>

<!–引入swagger-ui包–>

<dependency>

<groupId>io.springfox</groupId>

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

<version>2.6.1</version>

</dependency>

 

}

<version>1.6</version>

@ApiModelProperty(value =
“记录修改时间”)

<!–
使用swagger-bootstrap-ui替换暗中同意的UI

return new
ApiInfoBuilder()

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

e.getMessage();

if(count <=0 ) {

e.printStackTrace();

*/

<artifactId>jackson-annotations</artifactId>

@ApiOperation(value =
“依据客商id查询客商详细消息”, notes =
“依据客商id查询客商详细音讯”)

<groupId>com.fasterxml.jackson.core</groupId>

<version>2.6.1</version>

@ApiModelProperty(value = “ID”)

@RequestMapping(value =
“/selectAllUsers”, method = RequestMethod.GET)

return “error.jsp”;

private String password;

int count = 0;

import
io.swagger.annotations.ApiOperation;

package com.vk.liyj.model;

  • @Api:修饰整个类,描述Controller的效果与利益
  • @ApiOperation:描述二个类的三个主意,可能说二个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来抽取参数
  • @ApiProperty:用对象吸取参数时,描述对象的叁个字段
  • @ApiResponse:HTTP响应当中1个描述
  • @ApiResponses:HTTP响应全部描述
  • @ApiIgnore:使用该注解忽视这么些API
  • @ApiError :爆发错误再次来到的音讯
  • @ApiParamImplicitL:八个呼吁参数
  • @ApiParamsImplicit 七个央浼参数

import
com.vk.liyj.service.UserInfoService;

.select()

public class
UserInfoController {

return
“userList.jsp”;

@ApiModel(value = “UserInfo”)

return
“userList.jsp”;

@RequestMapping(value =
“update”, method = RequestMethod.POST)

}

2、创建swager配置类

<dependency>

import
org.springframework.format.annotation.DateTimeFormat;

集成步骤

public class UserInfo {

@ApiOperation(value =
“查询全数的职员音讯”, notes = “查询全体的人口音信”)

return updateTime;

import
javax.servlet.http.HttpServletRequest;

经过@Configuration表明,注脚它是贰个配置类,@EnableSwagger2开启swagger2。apiINfo()配置部分为主的新闻。apis()钦命扫描的包会生成文书档案。

@ApiImplicitParam(name =
“id”, value = “用户id”, required = true, paramType = “query”)

} else {

/**

return createTime;

</dependency>

e.getMessage();

<groupId>io.springfox</groupId>

import
javax.servlet.http.HttpServletResponse;

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

* 类描述:人士为主音讯

<version>2.6.1</version>

.apis(RequestHandlerSelectors

</dependency>

private String spellName;

private Integer userGender;

https://gitee.com/xiaoym/swagger-bootstrap-ui

*

4、调整器类

public Date getCreateTime() {

</dependency>

@ApiModelProperty(value = “客商登入账号”,
required = true)

return “error.jsp”;

<artifactId>jackson-core</artifactId>

import
springfox.documentation.builders.PathSelectors;

<groupId>com.fasterxml.jackson.core</groupId>

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

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

.apiInfo(apiInfo())

</dependency>

count =
service.insertSelective(user);

<groupId>com.github.xiaoymin</groupId>

return
“userUpdate.jsp”;

import
springfox.documentation.builders.ApiInfoBuilder;

package
com.vk.liyj.controller;

<artifactId>swagger-bootstrap-ui</artifactId>

@RequestMapping(value =
“add”, method = RequestMethod.POST)

return
“userList.jsp”;

@RequestMapping(value =
“/userInfo”)

public String
add(HttpServletRequest request, HttpServletResponse response, UserInfo
user) {

@RequestMapping(value =
“selectById”, method = RequestMethod.GET)

int count = 0;

<dependency>

import
com.fasterxml.jackson.annotation.JsonFormat;

swagger通过申明表明该接口会转移文书档案,饱含接口名、央求方法、参数、重回信息的等等。

1、在pom.xml中引耗费swagger信任包

@ApiOperation(value =
“根据客户id修改顾客音讯”, notes = “遵照客户id修改客商音信”)

})

}

3、编写swagger注解

@ApiOperation(value =
“依据客商id删除客户消息”, notes = “依照客户id删除客户信息”)

}

import
io.swagger.annotations.Api;

//
.apis(RequestHandlerSelectors.basePackage(“com.vk.liyj”))

e.getMessage();

}

}

<version>2.6.5</version>

return “error.jsp”;

@Autowired

<groupId>com.fasterxml.jackson.core</groupId>

//@EnableWebMvc //
启用Mvc,非springboot框架必要引进注解@EnableWebMvc

.termsOfServiceUrl(“”)

<groupId>io.springfox</groupId>

@JsonFormat(locale = “zh”, timezone =
“GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”)

//
扫描全体有注脚的api,用这种办法更加灵敏

<artifactId>springfox-swagger2</artifactId>

}

.withMethodAnnotation(ApiOperation.class))

</dependency>

return “error.jsp”;

import
org.springframework.context.annotation.Bean;

} else {

发表评论

电子邮件地址不会被公开。 必填项已用*标注