博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMVC+Swagger详细整合
阅读量:5945 次
发布时间:2019-06-19

本文共 34307 字,大约阅读时间需要 114 分钟。

一、新建maven工程导入正确的pom文件

还是那句话,包导入正确就成功了80%。剩下的20%慢慢攻克吧。

4.0.0
com.apidoc.demotest
apidoc
0.0.1-SNAPSHOT
war
4.1.7.RELEASE
2.4.4
2.2.2
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-core
${spring.version}
com.mangofactory
swagger-springmvc
1.0.2
com.fasterxml.jackson.core
jackson-annotations
${version.jackson}
com.fasterxml.jackson.core
jackson-databind
${version.jackson}
com.fasterxml.jackson.core
jackson-core
${version.jackson}
io.springfox
springfox-swagger2
${swagger.version}
io.springfox
springfox-swagger-ui
2.5.0
javax.servlet
javax.servlet-api
provided
3.1.0
io.springfox
springfox-petstore
${swagger.version}
org.springframework
spring-web
4.1.9.RELEASE
log4j
log4j
1.2.17
ch.qos.logback
logback-classic
1.1.2
ch.qos.logback
logback-core
1.1.2
org.logback-extensions
logback-ext-spring
0.1.1
net.sf.json-lib
json-lib
2.4
jdk15
org.apache.maven.plugins
maven-compiler-plugin
2.0.2
1.8
1.8

 二、建包并创建对应java文件

(1)

package com.apidoc.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import com.mangofactory.swagger.configuration.SpringSwaggerConfig;import com.mangofactory.swagger.models.dto.ApiInfo;import com.mangofactory.swagger.plugin.EnableSwagger;import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;@Configuration@EnableSwagger@EnableWebMvcpublic class SwaggerConfig {    private SpringSwaggerConfig springSwaggerConfig;    /**     * Required to autowire SpringSwaggerConfig     */    @Autowired    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {        this.springSwaggerConfig = springSwaggerConfig;    }    /**     * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc     * framework - allowing for multiple swagger groups i.e. same code base     * multiple swagger resource listings.     */    @Bean    public SwaggerSpringMvcPlugin customImplementation() {        // 暂时不用过滤        /*return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns(".*pet.*");*/        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo());    }    private ApiInfo apiInfo() {        ApiInfo apiInfo = new ApiInfo(                  "My Apps API Title",                  "My Apps API Description",                  "My Apps API terms of service",                  "My Apps API Contact Email",                  "My Apps API Licence Type",                  "My Apps API License URL"            );        return apiInfo;    }}

 

 

 (2)

package com.apidoc.model;public class User{        private String Id; private String Name; private Integer Age; public String getId() { return Id; } public void setId(String id) { Id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public Integer getAge() { return Age; } public void setAge(Integer age) { Age = age; } }

(3)

package com.apidoc.webservice;import javax.servlet.http.HttpServletRequest;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 org.springframework.web.bind.annotation.ResponseBody; import com.apidoc.model.User; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import net.sf.json.JSONObject; /** * @moudle: WebServiceForCSS * @version:v1.0 * @Description: TODO * @author: xukai * @date: 2016年12月1日 下午5:37:30 * */ @Controller public class WebServiceForCSS { @ResponseBody @RequestMapping(value = "getUserById", method = RequestMethod.GET, produces = {"application/json; charset=utf-8","application/xml"}) @ApiOperation(value = "通过ID查询USER信息", httpMethod = "POST", notes = "暂无") public String getUserById( @ApiParam(required = true, name = "id", value = "ID") @RequestParam(value = "id") String id,HttpServletRequest request) { User user = new User(); user.setId(id); user.setName("测试人员"); user.setAge(25); JSONObject object = JSONObject.fromObject(user); return object.toString(); } }

 

三、根据web.xml建立spring文件夹以及springmvc和spring相关的xml文件

SwaggerDemo
contextConfigLocation
classpath:spring/application-config.xml
org.springframework.web.context.ContextLoaderListener
dispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/mvc-config.xml
1
dispatcherServlet
/
default
*.jpg
default
*.png
default
*.gif
default
*.ico
default
*.js
default
*.css
default
*.html
default
*.xls
default
*.doc
default
*.json
default
*.eot
default
*.svg
default
*.ttf
default
*.woff
default
*.woff2
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp

 

 

在上述的基础上开始建立xml配置文件

(1)

 

 

 

(2)

 

四、进入swagger相关的github网站下载的swagger版本

网址如下:

https://github.com/swagger-api/swagger-ui

下载成功后,将dist目录拷贝到webapp目录下

拷贝成功后,将拷贝的dist目录下的index.html文件中的url修改为自己项目文档路径

Swagger UI

 

 五、新建一个json文件,配置如下

{    "swagger": "2.0",    "info": {        "description": "swagger-ui的汉化版本",        "version": "1.0.0",        "title": "汉化版Swagger-UI",        "termsOfService": "http://swagger.io/terms/",        "contact": {            "email": "helei5200@126.com"        },        "license": {            "name": "Apache 2.0",            "url": "http://www.apache.org/licenses/LICENSE-2.0.html"        }    },    "host": "petstore.swagger.io",    "basePath": "/v2",    "tags": [        {            "name": "pet",            "description": "有关你宠物的所有事情!",            "externalDocs": {                "description": "Find out more",                "url": "http://swagger.io"            }        },        {            "name": "store",            "description": "访问宠物商店订单!"        },        {            "name": "user",            "description": "操作用户相关!",            "externalDocs": {                "description": "Find out more about our store",                "url": "http://swagger.io"            }        }    ],    "schemes": [        "http"    ],    "paths": {        "/pet": {            "post": {                "tags": [                    "pet"                ],                "summary": "添加一个新宠物到商店!",                "description": "",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "addUser",                "consumes": [                    "application/json",                    "application/xml"                ],                "produces": [                    "application/xml",                    "application/json"                ],                "parameters": [                    {                        "in": "body",                        "name": "body",                        "description": "Pet object that needs to be added to the store",                        "required": true,                        "schema": {                            "$ref": "#/definitions/Pet"                        }                    }                ],                "responses": {                    "405": {                        "description": "Invalid input"                    }                },                "security": [                    {                        "petstore_auth": [                            "write:pets",                            "read:pets"                        ]                    }                ]            },            "put": {                "tags": [                    "pet"                ],                "summary": "更新存在的宠物信息",                "description": "",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "updatePet",                "consumes": [                    "application/json",                    "application/xml"                ],                "produces": [                    "application/xml",                    "application/json"                ],                "parameters": [                    {                        "in": "body",                        "name": "body",                        "description": "Pet object that needs to be added to the store",                        "required": true,                        "schema": {                            "$ref": "#/definitions/Pet"                        }                    }                ],                "responses": {                    "400": {                        "description": "Invalid ID supplied"                    },                    "404": {                        "description": "Pet not found"                    },                    "405": {                        "description": "Validation exception"                    }                },                "security": [                    {                        "petstore_auth": [                            "write:pets",                            "read:pets"                        ]                    }                ]            }        },        "/pet/findByStatus": {            "get": {                "tags": [                    "pet"                ],                "summary": "根据状态查找宠物",                "description": "Multiple status values can be provided with comma seperated strings",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "findPetsByStatus",                "produces": [                    "application/xml",                    "application/json"                ],                "parameters": [                    {                        "name": "status",                        "in": "query",                        "description": "Status values that need to be considered for filter",                        "required": true,                        "type": "array",                        "items": {                            "type": "string",                            "enum": [                                "available",                                "pending",                                "sold"                            ],                            "default": "available"                        },                        "collectionFormat": "csv"                    }                ],                "responses": {                    "200": {                        "description": "successful operation",                        "schema": {                            "type": "array",                            "items": {                                "$ref": "#/definitions/Pet"                            }                        }                    },                    "400": {                        "description": "Invalid status value"                    }                },                "security": [                    {                        "petstore_auth": [                            "write:pets",                            "read:pets"                        ]                    }                ]            }        },        "/pet/findByTags": {            "get": {                "tags": [                    "pet"                ],                "summary": "根据tags查找宠物",                "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "findPetsByTags",                "produces": [                    "application/xml",                    "application/json"                ],                "parameters": [                    {                        "name": "tags",                        "in": "query",                        "description": "Tags to filter by",                        "required": true,                        "type": "array",                        "items": {                            "type": "string"                        },                        "collectionFormat": "csv"                    }                ],                "responses": {                    "200": {                        "description": "successful operation",                        "schema": {                            "type": "array",                            "items": {                                "$ref": "#/definitions/Pet"                            }                        }                    },                    "400": {                        "description": "Invalid tag value"                    }                },                "security": [                    {                        "petstore_auth": [                            "write:pets",                            "read:pets"                        ]                    }                ]            }        },        "/pet/{petId}": {            "get": {                "tags": [                    "pet"                ],                "summary": "根据id查找宠物",                "description": "Returns a single pet",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "getPetById",                "produces": [                    "application/xml",                    "application/json"                ],                "parameters": [                    {                        "name": "petId",                        "in": "path",                        "description": "ID of pet to return",                        "required": true,                        "type": "integer",                        "format": "int64"                    }                ],                "responses": {                    "200": {                        "description": "successful operation",                        "schema": {                            "$ref": "#/definitions/Pet"                        }                    },                    "400": {                        "description": "Invalid ID supplied"                    },                    "404": {                        "description": "Pet not found"                    }                },                "security": [                    {                        "api_key": []                    }                ]            },            "post": {                "tags": [                    "pet"                ],                "summary": "根据表单数据,更新宠物数据",                "description": "",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "updatePetWithForm",                "consumes": [                    "application/x-www-form-urlencoded"                ],                "produces": [                    "application/xml",                    "application/json"                ],                "parameters": [                    {                        "name": "petId",                        "in": "path",                        "description": "ID of pet that needs to be updated",                        "required": true,                        "type": "integer",                        "format": "int64"                    },                    {                        "name": "name",                        "in": "formData",                        "description": "Updated name of the pet",                        "required": false,                        "type": "string"                    },                    {                        "name": "status",                        "in": "formData",                        "description": "Updated status of the pet",                        "required": false,                        "type": "string"                    }                ],                "responses": {                    "405": {                        "description": "Invalid input"                    }                },                "security": [                    {                        "petstore_auth": [                            "write:pets",                            "read:pets"                        ]                    }                ]            },            "delete": {                "tags": [                    "pet"                ],                "summary": "删除宠物",                "description": "",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "deletePet",                "produces": [                    "application/xml",                    "application/json"                ],                "parameters": [                    {                        "name": "api_key",                        "in": "header",                        "required": false,                        "type": "string"                    },                    {                        "name": "petId",                        "in": "path",                        "description": "Pet id to delete",                        "required": true,                        "type": "integer",                        "format": "int64"                    }                ],                "responses": {                    "400": {                        "description": "Invalid pet value"                    }                },                "security": [                    {                        "petstore_auth": [                            "write:pets",                            "read:pets"                        ]                    }                ]            }        },        "/pet/{petId}/uploadImage": {            "post": {                "tags": [                    "pet"                ],                "summary": "更新图片",                "description": "",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "uploadFile",                "consumes": [                    "multipart/form-data"                ],                "produces": [                    "application/json"                ],                "parameters": [                    {                        "name": "petId",                        "in": "path",                        "description": "ID of pet to update",                        "required": true,                        "type": "integer",                        "format": "int64"                    },                    {                        "name": "additionalMetadata",                        "in": "formData",                        "description": "Additional data to pass to server",                        "required": false,                        "type": "string"                    },                    {                        "name": "file",                        "in": "formData",                        "description": "file to upload",                        "required": false,                        "type": "file"                    }                ],                "responses": {                    "200": {                        "description": "successful operation",                        "schema": {                            "$ref": "#/definitions/ApiResponse"                        }                    }                },                "security": [                    {                        "petstore_auth": [                            "write:pets",                            "read:pets"                        ]                    }                ]            }        },        "/store/inventory": {            "get": {                "tags": [                    "store"                ],                "summary": "返回宠物库存状态",                "description": "Returns a map of status codes to quantities",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "getInventory",                "produces": [                    "application/json"                ],                "parameters": [],                "responses": {                    "200": {                        "description": "successful operation",                        "schema": {                            "type": "object",                            "additionalProperties": {                                "type": "integer",                                "format": "int32"                            }                        }                    }                },                "security": [                    {                        "api_key": []                    }                ]            }        },        "/store/order": {            "post": {                "tags": [                    "store"                ],                "summary": "订购一个宠物",                "description": "",                "author": "helei 更新于 2015/06/17 19:56",                "operationId": "placeOrder",                "produces": [                    "application/xml",                    "application/json"                ],                "parameters": [                    {                        "in": "body",                        "name": "body",                        "description": "order placed for purchasing the pet",                        "required": true,                        "schema": {                            "$ref": "#/definitions/Order"                        }                    }                ],                "responses": {                    "200": {                        "description": "successful operation",                        "schema": {                            "$ref": "#/definitions/Order"                        }                    },                    "400": {                        "description": "Invalid Order"                    }                }            }        },        "/store/order/{orderId}": {            "get": {                "tags": [                    "store"                ],                "summary": "根据ID查找订单",                "description": "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", "author": "helei 更新于 2015/06/17 19:56", "operationId": "getOrderById", "produces": [ "application/xml", "application/json" ], "parameters": [ { "name": "orderId", "in": "path", "description": "ID of pet that needs to be fetched", "required": true, "type": "integer", "maximum": 5, "minimum": 1, "format": "int64" } ], "responses": { "200": { "description": "successful operation", "schema": { "$ref": "#/definitions/Order" } }, "400": { "description": "Invalid ID supplied" }, "404": { "description": "Order not found" } } }, "delete": { "tags": [ "store" ], "summary": "根据ID删除订单", "description": "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", "author": "helei 更新于 2015/06/17 19:56", "operationId": "deleteOrder", "produces": [ "application/xml", "application/json" ], "parameters": [ { "name": "orderId", "in": "path", "description": "ID of the order that needs to be deleted", "required": true, "type": "string", "minimum": 1 } ], "responses": { "400": { "description": "Invalid ID supplied" }, "404": { "description": "Order not found" } } } }, "/user": { "post": { "tags": [ "user" ], "summary": "创建用户", "description": "This can only be done by the logged in user.", "author": "helei 更新于 2015/06/17 19:56", "operationId": "createUser", "produces": [ "application/xml", "application/json" ], "parameters": [ { "in": "body", "name": "body", "description": "Created user object", "required": true, "schema": { "$ref": "#/definitions/User" } } ], "responses": { "default": { "description": "successful operation" } } } }, "/user/createWithArray": { "post": { "tags": [ "user" ], "summary": "根据传入数组,创建多个用户", "description": "", "author": "helei 更新于 2015/06/17 19:56", "operationId": "createUsersWithArrayInput", "produces": [ "application/xml", "application/json" ], "parameters": [ { "in": "body", "name": "body", "description": "List of user object", "required": true, "schema": { "type": "array", "items": { "$ref": "#/definitions/User" } } } ], "responses": { "default": { "description": "successful operation" } } } }, "/user/createWithList": { "post": { "tags": [ "user" ], "summary": "根据列表创建多个用户", "description": "", "author": "helei 更新于 2015/06/17 19:56", "operationId": "createUsersWithListInput", "produces": [ "application/xml", "application/json" ], "parameters": [ { "in": "body", "name": "body", "description": "List of user object", "required": true, "schema": { "type": "array", "items": { "$ref": "#/definitions/User" } } } ], "responses": { "default": { "description": "successful operation" } } } }, "/user/login": { "get": { "tags": [ "user" ], "summary": "用户登录系统", "description": "", "author": "helei 更新于 2015/06/17 19:56", "operationId": "loginUser", "produces": [ "application/xml", "application/json" ], "parameters": [ { "name": "username", "in": "query", "description": "The user name for login", "required": true, "type": "string" }, { "name": "password", "in": "query", "description": "The password for login in clear text", "required": true, "type": "string" } ], "responses": { "200": { "description": "successful operation", "schema": { "type": "string" }, "headers": { "X-Rate-Limit": { "type": "integer", "format": "int32", "description": "calls per hour allowed by the user" }, "X-Expires-After": { "type": "string", "format": "date-time", "description": "date in UTC when toekn expires" } } }, "400": { "description": "Invalid username/password supplied" } } } }, "/user/logout": { "get": { "tags": [ "user" ], "summary": "用户退出登录,并清除session", "description": "", "author": "helei 更新于 2015/06/17 19:56", "operationId": "logoutUser", "produces": [ "application/xml", "application/json" ], "parameters": [], "responses": { "default": { "description": "successful operation" } } } }, "/user/{username}": { "get": { "tags": [ "user" ], "summary": "根据用户名获取用户", "description": "", "author": "helei 更新于 2015/06/17 19:56", "operationId": "getUserByName", "produces": [ "application/xml", "application/json" ], "parameters": [ { "name": "username", "in": "path", "description": "The name that needs to be fetched. Use user1 for testing. ", "required": true, "type": "string" } ], "responses": { "200": { "description": "successful operation", "schema": { "$ref": "#/definitions/User" } }, "400": { "description": "Invalid username supplied" }, "404": { "description": "User not found" } } }, "put": { "tags": [ "user" ], "summary": "更新用户", "author": "helei 更新于 2015/06/17 19:56", "description": "This can only be done by the logged in user.", "operationId": "updateUser", "produces": [ "application/xml", "application/json" ], "parameters": [ { "name": "username", "in": "path", "description": "name that need to be deleted", "required": true, "type": "string" }, { "in": "body", "name": "body", "description": "Updated user object", "required": true, "schema": { "$ref": "#/definitions/User" } } ], "responses": { "400": { "description": "Invalid user supplied" }, "404": { "description": "User not found" } } }, "delete": { "tags": [ "user" ], "summary": "删除用户", "author": "helei 更新于 2015/06/17 19:56", "description": "This can only be done by the logged in user.", "operationId": "deleteUser", "produces": [ "application/xml", "application/json" ], "parameters": [ { "name": "username", "in": "path", "description": "The name that needs to be deleted", "required": true, "type": "string" } ], "responses": { "400": { "description": "Invalid username supplied" }, "404": { "description": "User not found" } } } } }, "securityDefinitions": { "petstore_auth": { "type": "oauth2", "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", "flow": "implicit", "scopes": { "write:pets": "modify pets in your account", "read:pets": "read your pets" } }, "api_key": { "type": "apiKey", "name": "api_key", "in": "header" } }, "definitions": { "Order": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "petId": { "type": "integer", "format": "int64" }, "quantity": { "type": "integer", "format": "int32" }, "shipDate": { "type": "string", "format": "date-time" }, "status": { "type": "string", "description": "Order Status", "enum": [ "placed", "approved", "delivered" ] }, "complete": { "type": "boolean", "default": false } }, "xml": { "name": "Order" } }, "Category": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" } }, "xml": { "name": "Category" } }, "User": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "username": { "type": "string" }, "firstName": { "type": "string" }, "lastName": { "type": "string" }, "email": { "type": "string" }, "password": { "type": "string" }, "phone": { "type": "string" }, "userStatus": { "type": "integer", "format": "int32", "description": "User Status" } }, "xml": { "name": "User" } }, "Tag": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" } }, "xml": { "name": "Tag" } }, "Pet": { "type": "object", "required": [ "name", "photoUrls" ], "properties": { "id": { "type": "integer", "format": "int64" }, "category": { "$ref": "#/definitions/Category" }, "name": { "type": "string", "example": "doggie" }, "photoUrls": { "type": "array", "xml": { "name": "photoUrl", "wrapped": true }, "items": { "type": "string" } }, "tags": { "type": "array", "xml": { "name": "tag", "wrapped": true }, "items": { "$ref": "#/definitions/Tag" } }, "status": { "type": "string", "description": "pet status in the store", "enum": [ "available", "pending", "sold" ] } }, "xml": { "name": "Pet" } }, "ApiResponse": { "type": "object", "properties": { "code": { "type": "integer", "format": "int32" }, "type": { "type": "string" }, "message": { "type": "string" } } } }, "externalDocs": { "description": "了解一下我们吧!", "url": "https://github.com/helei112g" } }

写完后,配置好后,maven build一下

然后打开浏览器输入相对应的网址:localhost:8080/apidoc 就会出来一个文档界面

文档界面出来后,根据自己需要,模仿swagger.json文件,自己修改添加删除改造成自己想要的那样

 

转载地址:http://tkdxx.baihongyu.com/

你可能感兴趣的文章
大照片背景在网页设计中应用的精美作品范例(下篇)
查看>>
Realtek 8192cu win8 驱动
查看>>
property 中的strong 与weak
查看>>
使用HDFS java api 创建文件出错。
查看>>
支持多个文档类型的文档视结构程序
查看>>
【原创】FIFO的基础和时序分析学习
查看>>
Nginx学习之十一-Nginx启动框架处理流程
查看>>
[置顶] 吃论扯谈---吃货和Office 365订阅的关系
查看>>
蓝桥杯 基础练习 十六进制转十进制(水题,进制转换)
查看>>
php有些系统会报错或提示 Cannot modify header information - headers already sent by
查看>>
从零開始开发Android版2048 (五) 撤销的实现
查看>>
OpenGL 4 : 一个漂亮的心 For you, My Love
查看>>
2007年硕士研究生面试时的英文自我介绍
查看>>
POJ1789:Truck History(Prim算法)
查看>>
SD卡
查看>>
使用servletAPI三种方式简单示例
查看>>
单片机不同晶振怎么计算延迟时间?
查看>>
视频会议十大开源项目排行
查看>>
SQL Server Management Studio 简单使用说明
查看>>
【前端】javascript判断undefined、null、NaN;字符串包含等
查看>>