美高梅游戏官网娱乐_美高梅手机登录网站

美高梅游戏官网娱乐是公司推出的企业级即时在线娱乐平台,美高梅手机登录网站业界专业、信誉最好的博彩网站,美高梅游戏官网娱乐拥有最高优惠活动和返水,拥有丰富的管理经验和专业的技术队.。

来自 编程 2019-10-22 15:12 的文章
当前位置: 美高梅游戏官网娱乐 > 编程 > 正文

举目四望钦赐包中的swagger注脚,化解财富系统财

Swagger2在SpringBoot境况下的接纳

购并步骤

1. 集成Swagger

1、在pom.xml中援引度swagger信赖包

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>

 

<dependency>

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
}

}

 

<groupId>io.springfox</groupId>

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  :地址中付出:@帕特hVariable获取

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

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

dataType

Long

String

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

name

 

吸取参数名

value

 

收起参数的含义描述

required

 

参数是还是不是必填

 

TRUE

必填

 

FALSE

非必填

defaultValue

 

默认值

ApiImplicitParam 与 ApiParam 的区别

ApiImplicitParam: 

  • 对Servlets也许非 JAX-猎豹CS6S的条件,只可以利用 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;

}

}

 

<artifactId>springfox-swagger2</artifactId>

1.4 访问调控台

 

按以下步骤配置,项目运营后拜访:

<version>2.6.1</version>

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

 

</dependency>

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

<dependency>

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>

 

 

<groupId>io.springfox</groupId>

2.2 创建index.adoc文件

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

内容:

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

 

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

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 汉化


<version>2.6.1</version>

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-32x32.png" sizes="32x32"/>

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

<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

</dependency>

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":"服务器重临"

});

劳苦功高告成!

<dependency>

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

<artifactId>jackson-core</artifactId>

<version>2.6.5</version>

</dependency>

<dependency>

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

<artifactId>jackson-databind</artifactId>

<version>2.6.5</version>

</dependency>

<dependency>

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

<artifactId>jackson-annotations</artifactId>

<version>2.6.5</version>

</dependency>

2、创建swager配置类

package com.vk.liyj.config;

import io.swagger.annotations.ApiOperation;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

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

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;

/**

* 类描述:配置swagger2信息

*/

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

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

@EnableSwagger2 // 启用Swagger2

public class Swagger2Config {

@Bean

public Docket createRestApi() {

return new Docket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo())

.select()

// 扫描钦定包中的swagger评释

// .apis(RequestHandlerSelectors.basePackage("com.vk.liyj"))

// 扫描全部有注解的api,用这种情势越来越灵敏

.apis(RequestHandlerSelectors

.withMethodAnnotation(ApiOperation.class))

.paths(PathSelectors.any()).build();

}

private ApiInfo apiInfo() {

return new ApiInfoBuilder()

.title("基础平台 RESTful APIs")

.description(

"基础平台 RESTful 风格的接口文档,内容详细,十分的大的缩减了前后端的沟通费用,相同的时间确定保障代码与文书档案保持中度生龙活虎致,非常大的滑坡维护文书档案的岁月。")

.termsOfServiceUrl("")

.contact("Xia").version("1.0.0").build();

}

}

透过@Configuration表明,评释它是一个配置类,@EnableSwagger2开启swagger2。apiINfo()配置部分为主的消息。apis()钦命扫描的包会生成文书档案。

3、编写swagger注解

package com.vk.liyj.model;

import io.swagger.annotations.ApiModel;

import io.swagger.annotations.ApiModelProperty;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonFormat;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import com.fasterxml.jackson.annotation.JsonInclude;

/**

* 职员音讯表 申明:@ApiModel 和 @ApiModelProperty 用于在经过对象吸取参数时在API文书档案中展示字段的认证

* 评释:@DateTimeFormat 和 @JsonFormat 用于在收到和再次来到日期格式时将其格式化 实体类对应的数据表为: user_info

*

*

*/

@JsonInclude(JsonInclude.Include.NON_NULL)

@JsonIgnoreProperties({ "handler", "hibernateLazyInitializer" })

@ApiModel(value = "UserInfo")

public class UserInfo {

@ApiModelProperty(value = "ID")

private Integer id;

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

private String userNo;

@ApiModelProperty(value = "姓名", required = true)

private String userName;

@ApiModelProperty(value = "姓名拼音")

private String spellName;

@ApiModelProperty(value = "密码", required = true)

private String password;

@ApiModelProperty(value = "手机号", required = true)

private String userPhone;

@ApiModelProperty(value = "性别")

private Integer userGender;

@ApiModelProperty(value = "记录创立时间")

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

private Date createTime;

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

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

private Date updateTime;

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

public Date getCreateTime() {

return createTime;

}

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

public Date getUpdateTime() {

return updateTime;

}

}

4、调节器类

package com.vk.liyj.controller;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiImplicitParam;

import io.swagger.annotations.ApiImplicitParams;

import io.swagger.annotations.ApiOperation;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

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

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.RequestParam;

import com.vk.liyj.model.UserInfo;

import com.vk.liyj.service.UserInfoService;

/**

* 类描述:人士基本音讯

*/

@Controller

@RequestMapping(value = "/userInfo")

@Api(value = "UserInfo", description = "职员基本新闻 ")

public class UserInfoController {

@Autowired

UserInfoService service;

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

@ApiOperation(value = "查询全数的人手新闻", notes = "查询全数的人口音信")

public String selectAllUsers(HttpServletRequest request, HttpServletResponse response) {

List<UserInfo> userList = service.selectAllUsers();

request.setAttribute("userList", userList);

return "userList.jsp";

}

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

@ApiOperation(value = "依照客户id查询客户详细消息", notes = "依据顾客id查询客商详细新闻")

@ApiImplicitParams({

@ApiImplicitParam(name = "type", value = "类型(修改:update;私下认可为查看)", required = false, paramType = "query"),

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

})

public String selectById(HttpServletRequest request, HttpServletResponse response,

@RequestParam(value = "id") Integer id, @RequestParam(value = "type") String type) {

UserInfo user = service.selectByPrimaryKey(id);

request.setAttribute("user", user);

if("update".equals(type)) {

return "userUpdate.jsp";

} else {

return "userView.jsp";

}

}

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

@ApiOperation(value = "遵照顾客id删除顾客消息", notes = "依据客户id删除客商消息")

@ApiImplicitParams({

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

})

public String deleteById(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "id") Integer id) {

int count = 0;

try {

count = service.deleteByPrimaryKey(id);

if(count <=0 ) {

return "error.jsp";

} else {

request.getRequestDispatcher("selectAllUsers").forward(request, response);

return "userList.jsp";

}

} catch (Exception e) {

e.getMessage();

e.printStackTrace();

return "error.jsp";

}

}

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

@ApiOperation(value = "加多顾客音信", notes = "增添客户消息")

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

int count = 0;

try {

count = service.insertSelective(user);

if(count <=0 ) {

return "error.jsp";

} else {

//POST央浼的办法无法一直转变到GET央浼的主意,须求重定向

response.sendRedirect("selectAllUsers");

return "userList.jsp";

}

} catch (Exception e) {

e.getMessage();

e.printStackTrace();

return "error.jsp";

}

}

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

@ApiOperation(value = "依据顾客id修改客商消息", notes = "依照顾客id修改顾客新闻")

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

int count = 0;

try {

count = service.updateByPrimaryKeySelective(user);

if(count <=0 ) {

return "error.jsp";

} else {

//POST诉求的点子不能够直接倒车到GET乞求的诀窍,必要重定向

response.sendRedirect("selectAllUsers");

return "userList.jsp";

}

} catch (Exception e) {

e.getMessage();

e.printStackTrace();

return "error.jsp";

}

}

}

swagger通过声明申明该接口会扭转文书档案,饱含接口名、诉求方法、参数、再次来到新闻的等等。

  • @Api:修饰整个类,描述Controller的功用
  • @ApiOperation:描述一个类的多个艺术,恐怕说二个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来采取参数
  • @ApiProperty:用对象收取参数时,描述对象的四个字段
  • @ApiResponse:HTTP响应此中1个描述
  • @ApiResponses:HTTP响应整体描述
  • @ApiIgnore:使用该表明忽视这些API
  • @ApiError :发生错误重返的新闻
  • @ApiParamImplicitL:贰个伸手参数
  • @ApiParamsImplicit 几个央浼参数

5、运转程序访谈 http://localhost:8080/spring-mvc/swagger-ui.html

6、替换暗中认可的UI

<dependency>

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

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

<version>1.6</version>

</dependency>

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

<dependency>

<groupId>io.springfox</groupId>

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

<version>2.6.1</version>

</dependency>

-->

轮换后拜谒路线:http://localhost:8080/web/doc.html

参照他事他说加以考察资料

http://blog.csdn.net/songanling/article/details/71079304

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

源码下载地址:

本文由美高梅游戏官网娱乐发布于编程,转载请注明出处:举目四望钦赐包中的swagger注脚,化解财富系统财

关键词: