-
Swagger
2020-05-26 09:28:29目录1、Swagger简介2、SpringBoot集成Swagger3、配置Swagger4、配置扫描接口 1、Swagger简介 前后端分离 前端 -> 前端控制层、视图层 后端 -> 后端控制层、服务层、数据访问层 前后端通过API进行交互 ...1、Swagger简介
前后端分离
-
前端 -> 前端控制层、视图层
-
后端 -> 后端控制层、服务层、数据访问层
-
前后端通过API进行交互
-
前后端相对独立且松耦合
产生的问题
- 前后端集成,前端或者后端无法做到“及时协商,尽早解决”,最终导致问题集中爆发。
解决方案
- 首先定义schema [ 计划的提纲 ],并实时跟踪最新的API,降低集成风险
Swagger
-
号称世界上最流行的API框架
-
Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新
-
直接运行,在线测试API
-
支持多种语言 (如:Java,PHP等)
-
官网:https://swagger.io/
2、SpringBoot集成Swagger
SpringBoot集成Swagger => springfox,两个jar包
-
Springfox-swagger2
-
swagger-springmvc
使用Swagger
要求:jdk 1.8 + 否则swagger2无法运行
步骤:
1、新建一个SpringBoot-web项目
2、添加Maven依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
3、编写HelloController,测试确保运行成功!
4、要使用Swagger,我们需要编写一个配置类-SwaggerConfig来配置 Swagger
@Configuration //配置类 @EnableSwagger2// 开启Swagger2的自动配置 public class SwaggerConfig { }
5、访问测试 :http://localhost:8080/swagger-ui.html ,可以看到swagger的界面;
3、配置Swagger
1、Swagger实例Bean是Docket,所以通过配置Docket实例来配置Swaggger。
@Bean //配置docket以配置Swagger具体参数 public Docket docket() { return new Docket(DocumentationType.SWAGGER_2); }
2、可以通过apiInfo()属性配置文档信息
//配置文档信息 private ApiInfo apiInfo() { Contact contact = new Contact("联系人名字", "http://xxx.xxx.com/联系人访问链接", "联系人邮箱"); return new ApiInfo( "Swagger学习", // 标题 "学习演示如何配置Swagger", // 描述 "v1.0", // 版本 "http://terms.service.url/组织链接", // 组织链接 contact, // 联系人信息 "Apach 2.0 许可", // 许可 "许可链接", // 许可连接 new ArrayList<>()// 扩展 ); }
演示:
//配置了Swagger信息=apiInfo private ApiInfo apiInfo(){ Contact contact = new Contact("一叶孤舟","https://www.csdn.net/","517394441@qq.com"); return new ApiInfo( "一叶孤舟的SwaggerAPI文档", "你要悄悄拔尖,然后惊艳所有人", "v1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); }
3、Docket 实例关联上 apiInfo()
@Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()); }
4、重启项目,访问测试 http://localhost:8080/swagger-ui.html 看下效果;
4、配置扫描接口
1、构建Docket时通过select()方法配置怎么扫描接口。
@Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口 .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .build(); }
2、重启项目测试,由于我们配置根据包的路径扫描接口,所以我们只能看到一个类
3、除了通过包路径配置扫描接口外,还可以通过配置其他方式扫描接口,这里注释一下所有的配置方式:
any() // 扫描所有,项目中的所有接口都会被扫描到 none() // 不扫描接口 // 通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求 withMethodAnnotation(final Class<? extends Annotation> annotation) // 通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口 withClassAnnotation(final Class<? extends Annotation> annotation) basePackage(final String basePackage) // 根据包路径扫描接口
4、除此之外,我们还可以配置接口扫描过滤:
@Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口 .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller")) // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口 .paths(PathSelectors.ant("/kuang/**")) .build(); }
5、这里的可选值还有
any() // 任何请求都扫描
none() // 任何请求都不扫描
regex(final String pathRegex) // 通过正则表达式控制
ant(final String antPattern) // 通过ant()控制
5、配置Swagger开关
1、通过enable()方法配置是否启用swagger,如果是false,swagger将不能在浏览器中访问了。
@Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(false) //配置是否启用Swagger,如果是false,在浏览器将无法访问 .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口 .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller")) // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口 .paths(PathSelectors.ant("/kuang/**")) .build(); }
效果:
2、如何动态配置当项目处于test、dev环境时显示swagger,处于prod时不显示?@Bean public Docket docket(Environment environment) { // 设置要显示swagger的环境 Profiles of = Profiles.of("dev", "test"); // 判断当前是否处于该环境 // 通过 enable() 接收此参数判断是否要显示 boolean b = environment.acceptsProfiles(of); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(b) //配置是否启用Swagger,如果是false,在浏览器将无法访问 .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口 .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller")) // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口 .paths(PathSelectors.ant("/kuang/**")) .build(); }
6、配置API分组
1、如果没有配置分组,默认是default。通过groupName()方法即可配置分组:
@Bean public Docket docket(Environment environment) { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .groupName("hello") // 配置分组 // 省略配置.... }
2、重启项目查看分组
3、如何配置多个分组?配置多个分组只需要配置多个docket即可:
@Bean public Docket docket1(){ return new Docket(DocumentationType.SWAGGER_2).groupName("group1"); } @Bean public Docket docket2(){ return new Docket(DocumentationType.SWAGGER_2).groupName("group2"); } @Bean public Docket docket3(){ return new Docket(DocumentationType.SWAGGER_2).groupName("group3"); }
4、重启项目查看即可
7、实体配置
1、新建一个实体类
@ApiModel("用户实体") public class User { @ApiModelProperty("用户名") public String username; @ApiModelProperty("密码") public String password; }
2、只要这个实体在请求接口的返回值上(即使是泛型),都能映射到实体项中:
@RequestMapping("/getUser") public User getUser(){ return new User(); }
3、重启查看测试
注:并不是因为@ApiModel这个注解让实体显示在这里了,而是只要出现在接口方法的返回值上的实体都会显示在这里,而@ApiModel和@ApiModelProperty这两个注解只是为实体添加注释的。@ApiModel为类添加注释
@ApiModelProperty为类属性添加注释
8、常用注解
Swagger的所有注解定义在io.swagger.annotations包下
下面列一些经常用到的,未列举出来的可以另行查阅说明:
Swagger注解 简单说明
@Api(tags = “xxx模块说明”) 作用在模块类上
@ApiOperation(“xxx接口说明”) 作用在接口方法上
@ApiModel(“xxxPOJO说明”) 作用在模型类上:如VO、BO
@ApiModelProperty(value = “xxx属性说明”,hidden = true) 作用在类方法和属性上,hidden设置为true可以隐藏该属性
@ApiParam(“xxx参数说明”) 作用在参数、方法和字段上,类似@ApiModelProperty我们也可以给请求的接口配置一些注释
@ApiOperation("狂神的接口") @PostMapping("/kuang") @ResponseBody public String kuang(@ApiParam("这个名字会被返回")String username){ return username; }
这样的话,可以给一些比较难理解的属性或者接口,增加一些配置信息,让人更容易阅读!
相较于传统的Postman或Curl方式测试接口,使用swagger简直就是傻瓜式操作,不需要额外说明文档(写得好本身就是文档)而且更不容易出错,只需要录入数据然后点击Execute,如果再配合自动化框架,可以说基本就不需要人为操作了。
Swagger是个优秀的工具,现在国内已经有很多的中小型互联网公司都在使用它,相较于传统的要先出Word接口文档再测试的方式,显然这样也更符合现在的快速迭代开发行情。当然了,提醒下大家在正式环境要记得关闭Swagger,一来出于安全考虑二来也可以节省运行时内存。
-
-
swagger
2019-06-11 11:12:31本文作者:小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119 实际项目中非常需要写文档,提高Java...一:Swagger介绍Swagger是当前最好用的Restful API文档生成的...实际项目中非常需要写文档,提高Java服务端和Web前端以及移动端的对接效率。听说Swagger这个工具,还不错,就网上找了些资料,自己实践了下。一:Swagger介绍
Swagger是当前最好用的Restful API文档生成的开源项目,通过swagger-spring项目
实现了与SpingMVC框架的无缝集成功能,方便生成spring restful风格的接口文档,
同时swagger-ui还可以测试spring restful风格的接口功能。
官方网站为:http://swagger.io/
二:Swagger与Spring MVC集成步骤1.Maven关键配置- <dependency>
- <groupId>com.mangofactory</groupId>
- <artifactId>swagger-springmvc</artifactId>
- <version>1.0.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>4.1.6.RELEASE</version>
- </dependency>
2. 插件配置CustomJavaPluginConfig3.复制swagger的相关js等静态资源到webapp目录。swagger-ui.js之类的。我copy过一次,但是有问题,最后从网上下载了一个项目,可以直接用的那种。然后自己再逐步改造。4.启动项目三、常见swagger注解一览与使用最常用的5个注解@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
其它若干
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiClass
@ApiError
@ApiErrors
@ApiParamImplicit
@ApiParamsImplicit
四、关键代码和实际例子例子1:- @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "list", method = RequestMethod.POST)
- public Result<User> list(
- @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId,
- @ApiParam(value = "token", required = true) @RequestParam String token) {
- Result<User> result = new Result<User>();
- User user = new User();
- result.setData(user);
- return result;
- }
@ApiParam(value = "token", required = true) @RequestParam String tokenWeb前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。例子2:- @ApiOperation(value = "update用户", notes = ")", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "update", method = RequestMethod.GET/*,produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE*/)
- public Result<String> update(User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
当参数太多的时候,需要定义太多的参数,排版看起来很不舒服。这个时候,可以使用对象来接收。@ApiModel(value = "用户对象",description="user2")public class User extends CommonParam{}Web前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。这里面存在一个小问题,当后端用对象User来接收参数的时候,Swagger自带的工具是这样的:这种形式,并不是表单提交,或者把参数附加到URL的后面。我们只能手动构造URL,附带参数去提交。如果需要测试的话!例子3:- public Result<String> add(@RequestBody User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
Web前端/移动端HTTP请求方式:必须把参数,放到request请求的body中去。后端不能直接用request.getParam("token")这种。获得request body中的数据,手动转换成目标数据。String charReader(HttpServletRequest request) throws IOException {BufferedReader br = request.getReader();String str, wholeStr = "";while ((str = br.readLine()) != null) {wholeStr += str;}return wholeStr;}个人推荐:1.参数不多的时候,用例子1,用@ApiParam注解生成文档。swagger可视化界面,可以直接设置参数,发送请求来测试2.参数比较多的时候,用例子2,用对象来接收参数,在对象里针对每个字段,@ApiModelProperty注解生成文档。swagger可视化界面,可以直接设置参数,但是无法接收到。因此,推荐使用其它HTTP请求或POST模拟工具,发送请求,模拟测试。不推荐例子3,不通用,局限性比较大。五、若干截图六、源代码- package cn.fansunion.swagger.serverapi.controller;
- import org.springframework.http.MediaType;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- 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.wordnik.swagger.annotations.Api;
- import com.wordnik.swagger.annotations.ApiOperation;
- import com.wordnik.swagger.annotations.ApiParam;
- /**
- * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119
- * 博客:http://blog.csdn.net/fansunion
- *
- */
- @Api(value = "user", description = "用户管理", produces = MediaType.APPLICATION_JSON_VALUE)
- @Controller
- @RequestMapping("user")
- public class UserController {
- // 列出某个类目的所有规格
- @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "list", method = RequestMethod.POST)
- public Result<User> list(
- @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId,
- @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId2,
- @ApiParam(value = "token", required = true) @RequestParam String token) {
- Result<User> result = new Result<User>();
- User user = new User();
- result.setData(user);
- return result;
- }
- @ApiOperation(value = "添加用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "add", method = RequestMethod.POST)
- // @RequestBody只能有1个
- // 使用了@RequestBody,不能在拦截器中,获得流中的数据,再json转换,拦截器中,也不清楚数据的类型,无法转换成java对象
- // 只能手动调用方法
- public Result<String> add(@RequestBody User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
- @ApiOperation(value = "update用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "update", method = RequestMethod.GET)
- public Result<String> update(User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
- private String findUser(User user) {
- String token = user.getToken();
- return token;
- }
- }
- package cn.fansunion.swagger.serverapi.controller;
- import com.wordnik.swagger.annotations.ApiModel;
- import com.wordnik.swagger.annotations.ApiModelProperty;
- /**
- * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119
- * 博客:http://blog.csdn.net/fansunion
- *
- */
- @ApiModel(value = "用户对象", description = "user2")
- public class User extends CommonParam {
- @ApiModelProperty(value = "商品信息", required = true)
- private String name;
- @ApiModelProperty(value = "密码", required = true)
- private String password;
- @ApiModelProperty(value = "性别")
- private Integer sex;
- @ApiModelProperty(value = "密码", required = true)
- private String token;
- public String getToken() {
- return token;
- }
- public void setToken(String token) {
- this.token = token;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public Integer getSex() {
- return sex;
- }
- public void setSex(Integer sex) {
- this.sex = sex;
- }
- }
- package cn.fansunion.swagger.serverapi.swagger;
- 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.DefaultServletHandlerConfigurer;
- import org.springframework.web.servlet.config.annotation.EnableWebMvc;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
- import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
- import com.mangofactory.swagger.models.dto.ApiInfo;
- import com.mangofactory.swagger.paths.SwaggerPathProvider;
- import com.mangofactory.swagger.plugin.EnableSwagger;
- import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
- @Configuration
- @EnableWebMvc
- @EnableSwagger
- public class CustomJavaPluginConfig extends WebMvcConfigurerAdapter {
- private SpringSwaggerConfig springSwaggerConfig;
- @Autowired
- public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
- this.springSwaggerConfig = springSwaggerConfig;
- }
- /**
- * 链式编程 来定制API样式 后续会加上分组信息
- *
- * @return
- */
- @Bean
- public SwaggerSpringMvcPlugin customImplementation() {
- return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
- .apiInfo(apiInfo()).includePatterns(".*")
- .useDefaultResponseMessages(false)
- // .pathProvider(new GtPaths())
- .apiVersion("0.1").swaggerGroup("user");
- }
- private ApiInfo apiInfo() {
- ApiInfo apiInfo = new ApiInfo("小雷移动端API接口平台",
- "提供详细的后台所有Restful接口", "http://blog.csdn.net/FansUnion",
- "FansUnion@qq.com", "小雷博客", "http://blog.csdn.net/FansUnion");
- return apiInfo;
- }
- @Override
- public void configureDefaultServletHandling(
- DefaultServletHandlerConfigurer configurer) {
- configurer.enable();
- }
- class GtPaths extends SwaggerPathProvider {
- @Override
- protected String applicationPath() {
- return "/restapi";
- }
- @Override
- protected String getDocumentationPath() {
- return "/restapi";
- }
- }
- }
七、项目下载地址八、参考资料实际项目中非常需要写文档,提高Java服务端和Web前端以及移动端的对接效率。听说Swagger这个工具,还不错,就网上找了些资料,自己实践了下。一:Swagger介绍
Swagger是当前最好用的Restful API文档生成的开源项目,通过swagger-spring项目
实现了与SpingMVC框架的无缝集成功能,方便生成spring restful风格的接口文档,
同时swagger-ui还可以测试spring restful风格的接口功能。
官方网站为:http://swagger.io/
二:Swagger与Spring MVC集成步骤1.Maven关键配置- <dependency>
- <groupId>com.mangofactory</groupId>
- <artifactId>swagger-springmvc</artifactId>
- <version>1.0.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>4.1.6.RELEASE</version>
- </dependency>
2. 插件配置CustomJavaPluginConfig3.复制swagger的相关js等静态资源到webapp目录。swagger-ui.js之类的。我copy过一次,但是有问题,最后从网上下载了一个项目,可以直接用的那种。然后自己再逐步改造。4.启动项目三、常见swagger注解一览与使用最常用的5个注解@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
其它若干
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiClass
@ApiError
@ApiErrors
@ApiParamImplicit
@ApiParamsImplicit
四、关键代码和实际例子例子1:- @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "list", method = RequestMethod.POST)
- public Result<User> list(
- @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId,
- @ApiParam(value = "token", required = true) @RequestParam String token) {
- Result<User> result = new Result<User>();
- User user = new User();
- result.setData(user);
- return result;
- }
@ApiParam(value = "token", required = true) @RequestParam String tokenWeb前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。例子2:- @ApiOperation(value = "update用户", notes = ")", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "update", method = RequestMethod.GET/*,produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE*/)
- public Result<String> update(User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
当参数太多的时候,需要定义太多的参数,排版看起来很不舒服。这个时候,可以使用对象来接收。@ApiModel(value = "用户对象",description="user2")public class User extends CommonParam{}Web前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。这里面存在一个小问题,当后端用对象User来接收参数的时候,Swagger自带的工具是这样的:这种形式,并不是表单提交,或者把参数附加到URL的后面。我们只能手动构造URL,附带参数去提交。如果需要测试的话!例子3:- public Result<String> add(@RequestBody User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
Web前端/移动端HTTP请求方式:必须把参数,放到request请求的body中去。后端不能直接用request.getParam("token")这种。获得request body中的数据,手动转换成目标数据。String charReader(HttpServletRequest request) throws IOException {BufferedReader br = request.getReader();String str, wholeStr = "";while ((str = br.readLine()) != null) {wholeStr += str;}return wholeStr;}个人推荐:1.参数不多的时候,用例子1,用@ApiParam注解生成文档。swagger可视化界面,可以直接设置参数,发送请求来测试2.参数比较多的时候,用例子2,用对象来接收参数,在对象里针对每个字段,@ApiModelProperty注解生成文档。swagger可视化界面,可以直接设置参数,但是无法接收到。因此,推荐使用其它HTTP请求或POST模拟工具,发送请求,模拟测试。不推荐例子3,不通用,局限性比较大。五、若干截图六、源代码- package cn.fansunion.swagger.serverapi.controller;
- import org.springframework.http.MediaType;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- 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.wordnik.swagger.annotations.Api;
- import com.wordnik.swagger.annotations.ApiOperation;
- import com.wordnik.swagger.annotations.ApiParam;
- /**
- * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119
- * 博客:http://blog.csdn.net/fansunion
- *
- */
- @Api(value = "user", description = "用户管理", produces = MediaType.APPLICATION_JSON_VALUE)
- @Controller
- @RequestMapping("user")
- public class UserController {
- // 列出某个类目的所有规格
- @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "list", method = RequestMethod.POST)
- public Result<User> list(
- @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId,
- @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId2,
- @ApiParam(value = "token", required = true) @RequestParam String token) {
- Result<User> result = new Result<User>();
- User user = new User();
- result.setData(user);
- return result;
- }
- @ApiOperation(value = "添加用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "add", method = RequestMethod.POST)
- // @RequestBody只能有1个
- // 使用了@RequestBody,不能在拦截器中,获得流中的数据,再json转换,拦截器中,也不清楚数据的类型,无法转换成java对象
- // 只能手动调用方法
- public Result<String> add(@RequestBody User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
- @ApiOperation(value = "update用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
- @ResponseBody
- @RequestMapping(value = "update", method = RequestMethod.GET)
- public Result<String> update(User user) {
- String u = findUser(user);
- System.out.println(u);
- return null;
- }
- private String findUser(User user) {
- String token = user.getToken();
- return token;
- }
- }
- package cn.fansunion.swagger.serverapi.controller;
- import com.wordnik.swagger.annotations.ApiModel;
- import com.wordnik.swagger.annotations.ApiModelProperty;
- /**
- * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119
- * 博客:http://blog.csdn.net/fansunion
- *
- */
- @ApiModel(value = "用户对象", description = "user2")
- public class User extends CommonParam {
- @ApiModelProperty(value = "商品信息", required = true)
- private String name;
- @ApiModelProperty(value = "密码", required = true)
- private String password;
- @ApiModelProperty(value = "性别")
- private Integer sex;
- @ApiModelProperty(value = "密码", required = true)
- private String token;
- public String getToken() {
- return token;
- }
- public void setToken(String token) {
- this.token = token;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public Integer getSex() {
- return sex;
- }
- public void setSex(Integer sex) {
- this.sex = sex;
- }
- }
- package cn.fansunion.swagger.serverapi.swagger;
- 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.DefaultServletHandlerConfigurer;
- import org.springframework.web.servlet.config.annotation.EnableWebMvc;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
- import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
- import com.mangofactory.swagger.models.dto.ApiInfo;
- import com.mangofactory.swagger.paths.SwaggerPathProvider;
- import com.mangofactory.swagger.plugin.EnableSwagger;
- import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
- @Configuration
- @EnableWebMvc
- @EnableSwagger
- public class CustomJavaPluginConfig extends WebMvcConfigurerAdapter {
- private SpringSwaggerConfig springSwaggerConfig;
- @Autowired
- public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
- this.springSwaggerConfig = springSwaggerConfig;
- }
- /**
- * 链式编程 来定制API样式 后续会加上分组信息
- *
- * @return
- */
- @Bean
- public SwaggerSpringMvcPlugin customImplementation() {
- return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
- .apiInfo(apiInfo()).includePatterns(".*")
- .useDefaultResponseMessages(false)
- // .pathProvider(new GtPaths())
- .apiVersion("0.1").swaggerGroup("user");
- }
- private ApiInfo apiInfo() {
- ApiInfo apiInfo = new ApiInfo("小雷移动端API接口平台",
- "提供详细的后台所有Restful接口", "http://blog.csdn.net/FansUnion",
- "FansUnion@qq.com", "小雷博客", "http://blog.csdn.net/FansUnion");
- return apiInfo;
- }
- @Override
- public void configureDefaultServletHandling(
- DefaultServletHandlerConfigurer configurer) {
- configurer.enable();
- }
- class GtPaths extends SwaggerPathProvider {
- @Override
- protected String applicationPath() {
- return "/restapi";
- }
- @Override
- protected String getDocumentationPath() {
- return "/restapi";
- }
- }
- }
七、项目下载地址八、参考资料 -
swagger 介绍及两种使用方法
2018-04-26 15:13:30一:swagger是什么? 1、是一款让你更好的书写API文档的规范且完整框架。 2、提供描述、生产、消费和可视化RESTful Web Service。 3、是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库...一:swagger是什么?
1、是一款让你更好的书写API文档规范且完整的框架。
2、提供描述、生产、消费和可视化RESTful Web Service。
3、是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面。方法一:使用第三方依赖(最简单的方法)
1、在pom.xml文件中添加第三方swagger依赖()
<dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.7.0.RELEASE</version> </dependency>
2、在Spring Boot项目的启动类上添加@EnableSwagger2Doc注解,就可以直接使用啦。
3、https://github.com/SpringForAll/spring-boot-starter-swagger这是GitHub上这个swagger依赖实现的项目,里面有详细的讲解。方法二:使用官方依赖
1、在pom.xml文件中添加swagger相关依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
第一个是API获取的包,第二是官方给出的一个ui界面。这个界面可以自定义,默认是官方的,对于安全问题,以及ui路由设置需要着重思考。
2、swagger的configuration
需要特别注意的是swagger scan base package,这是扫描注解的配置,即你的API接口位置。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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 Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.yss.ms.admin")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("服务:发布为daocke镜像,权限管理,用户管理,页面管理,日志 后台 APIs") .description("服务:发布为daocke镜像,权限管理,用户管理,页面管理,日志 后台") .termsOfServiceUrl("http://192.168.1.198:10070/platformgroup/ms-admin") .contact("程序猿") .version("1.0") .build(); } }
三、具体使用
1、在API上做一些声明
//本controller的功能描述 @Api(value = "pet", description = "the pet API") public interface PetApi { //option的value的内容是这个method的描述,notes是详细描述,response是最终返回的json model。其他可以忽略 @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) //这里是显示你可能返回的http状态,以及原因。比如404 not found, 303 see other @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/pet", produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) ResponseEntity<Void> addPet( //这里是针对每个参数的描述 @ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
2、设定访问API doc的路由
在配置文件中,application.yml中声明:
springfox.documentation.swagger.v2.path: /api-docs
这个path就是json的访问request mapping.可以自定义,防止与自身代码冲突。
API doc的显示路由是:http://localhost:8080/swagger-ui.html
如果项目是一个webservice,通常设定home / 指向这里:
@Controller public class HomeController { @RequestMapping(value = "/swagger") public String index() { System.out.println("swagger-ui.html"); return "redirect:swagger-ui.html"; } }
四:swagger的常用API
1、api标记
Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:
@Api(value = "/user", description = "Operations about user")
2、ApiOperation标记
ApiOperation:用在方法上,说明方法的作用,每一个url资源的定义,使用方式:
@ApiOperation( value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order, tags = {"Pet Store"})
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V8AEIZ2l-1609508640724)(http://ozpb6wow8.bkt.clouddn.com/22.png)]
3、ApiParam标记
ApiParam请求属性,使用方式:
public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5veQGqo7-1609508640725)(http://ozpb6wow8.bkt.clouddn.com/3.png)]
4、ApiResponse
ApiResponse:响应配置,使用方式:
@ApiResponse(code = 400, message = "Invalid user supplied")
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6nd1sH5D-1609508640729)(http://ozpb6wow8.bkt.clouddn.com/44.png)]5、ApiResponses
ApiResponses:响应集配置,使用方式:
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SNlJ6vSI-1609508640730)(http://ozpb6wow8.bkt.clouddn.com/5.png)]6、ResponseHeader
响应头设置,使用方法
@ResponseHeader(name="head1",description="response head conf")
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NDXgB4JA-1609508640731)(http://ozpb6wow8.bkt.clouddn.com/6.png)] -
Swagger使用指南
2018-06-03 11:39:091:认识Swagger Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端...1:认识Swagger
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
作用:
1. 接口的文档在线自动生成。
2. 功能测试。
Swagger是一组开源项目,其中主要要项目如下:
1. Swagger-tools:提供各种与Swagger进行集成和交互的工具。例如模式检验、Swagger 1.2文档转换成Swagger 2.0文档等功能。
2. Swagger-core: 用于Java/Scala的的Swagger实现。与JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架进行集成。
3. Swagger-js: 用于JavaScript的Swagger实现。
4. Swagger-node-express: Swagger模块,用于node.js的Express web应用框架。
5. Swagger-ui:一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档。
6. Swagger-codegen:一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码。
2:Maven
版本号请根据实际情况自行更改。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
3:创建Swagger2配置类
在Application.java同级创建Swagger2的配置类Swagger2
package com.swaggerTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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配置类 * 在与spring boot集成时,放在与Application.java同级的目录下。 * 通过@Configuration注解,让Spring来加载该类配置。 * 再通过@EnableSwagger2注解来启用Swagger2。 */ @Configuration @EnableSwagger2 public class Swagger2 { /** * 创建API应用 * apiInfo() 增加API相关信息 * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现, * 本例采用指定扫描的包路径来定义指定要建立API的目录。 * * @return */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller")) .paths(PathSelectors.any()) .build(); } /** * 创建该API的基本信息(这些基本信息会展现在文档页面中) * 访问地址:http://项目实际地址/swagger-ui.html * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs") .description("更多请关注http://www.baidu.com") .termsOfServiceUrl("http://www.baidu.com") .contact("sunf") .version("1.0") .build(); } }
如上代码所示,通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
4:添加文档内容
在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,描述的主要来源是函数的命名,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。
Swagger使用的注解及其说明:
@Api:用在类上,说明该类的作用。
@ApiOperation:注解来给API增加方法说明。
@ApiImplicitParams : 用在方法上包含一组参数说明。
@ApiImplicitParam:用来注解来给方法入参增加说明。
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
l code:数字,例如400
l message:信息,例如"请求参数没填好"
l response:抛出异常的类
@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
l @ApiModelProperty:描述一个model的属性
注意:@ApiImplicitParam的参数说明:
paramType:指定参数放在哪个地方
header:请求参数放置于Request Header,使用@RequestHeader获取
query:请求参数放置于请求地址,使用@RequestParam获取
path:(用于restful接口)-->请求参数的获取:@PathVariable
body:(不常用)
form(不常用)
name:参数名
dataType:参数类型
required:参数是否必须传
true | false
value:说明参数的意思
defaultValue:参数的默认值
例子:
package com.swaggerTest.controller; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; 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 io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; /** * 一个用来测试swagger注解的控制器 * 注意@ApiImplicitParam的使用会影响程序运行,如果使用不当可能造成控制器收不到消息 * * @author SUNF */ @Controller @RequestMapping("/say") @Api(value = "SayController|一个用来测试swagger注解的控制器") public class SayController { @ResponseBody @RequestMapping(value ="/getUserName", method= RequestMethod.GET) @ApiOperation(value="根据用户编号获取用户姓名", notes="test: 仅1和2有正确返回") @ApiImplicitParam(paramType="query", name = "userNumber", value = "用户编号", required = true, dataType = "Integer") public String getUserName(@RequestParam Integer userNumber){ if(userNumber == 1){ return "张三丰"; } else if(userNumber == 2){ return "慕容复"; } else{ return "未知"; } } @ResponseBody @RequestMapping("/updatePassword") @ApiOperation(value="修改用户密码", notes="根据用户id修改密码") @ApiImplicitParams({ @ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "Integer"), @ApiImplicitParam(paramType="query", name = "password", value = "旧密码", required = true, dataType = "String"), @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密码", required = true, dataType = "String") }) public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password, @RequestParam(value="newPassword") String newPassword){ if(userId <= 0 || userId > 2){ return "未知的用户"; } if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){ return "密码不能为空"; } if(password.equals(newPassword)){ return "新旧密码不能相同"; } return "密码修改成功!"; } }
完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html
如上图,可以看到暴漏出来的控制器信息,点击进入可以看到详细信息。
两个注意点:
1. paramType会直接影响程序的运行期,如果paramType与方法参数获取使用的注解不一致,会直接影响到参数的接收。
例如:
使用Sawgger UI进行测试,接收不到!
2. 还有一个需要注意的地方:
Conntroller中定义的方法必须在@RequestMapper中显示的指定RequestMethod类型,否则SawggerUi会默认为全类型皆可访问, API列表中会生成多条项目。
如上图:updatePassword()未指定requestMethod,结果生成了7条API信息。所以如果没有特殊需求,建议根据实际情况加上requestMethod。
5:Swagger UI面板说明
6:参考
http://blog.didispace.com/springbootswagger2/
http://blog.csdn.net/jia20003/article/details/50700736
Swagger官网 :http://swagger.io/
Spring Boot & Swagger UI : http://fruzenshtein.com/spring-boot-swagger-ui/
Github:https://github.com/swagger-api/swagger-core/wiki/Annotations
---------------------------------------------------------------------------------------
7:接收对象传参的例子
在POJO上增加
package com.zhongying.api.model.base; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * 医生对象模型,不要使用该类 * @author SUNF * */ @ApiModel(value="医生对象模型") public class DemoDoctor{ @ApiModelProperty(value="id" ,required=true) private Integer id; @ApiModelProperty(value="医生姓名" ,required=true) private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "DemoDoctor [id=" + id + ", name=" + name + "]"; } }
注意: 在后台采用对象接收参数时,Swagger自带的工具采用的是JSON传参, 测试时需要在参数上加入@RequestBody,正常运行采用form或URL提交时候请删除。
package com.zhongying.api.controller.app; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; 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.github.pagehelper.PageInfo; import com.zhongying.api.exception.HttpStatus401Exception; import com.zhongying.api.model.base.DemoDoctor; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; /** * 医生类(模拟) * @author SUNF */ @RequestMapping("/api/v1") @Controller @Api(value = "DoctorTestController-医生信息接口模拟") public class DoctorTestController { /** * 添加医生 * * 在使用对象封装参数进行传参时,需要在该对象添加注解,将其注册到swagger中 * @link com.zhongying.api.model.base.DemoDoctor * * 注意: 在后台采用对象接收参数时,Swagger自带的工具采用的是JSON传参, * 测试时需要在参数上加入@RequestBody,正常运行采用form或URL提交时候请删除。 * * @param doctor 医生类对象 * @return * @throws Exception */ @ResponseBody @RequestMapping(value="/doctor", method= RequestMethod.POST ) @ApiOperation(value="添加医生信息", notes="") public String addDoctor(@RequestBody DemoDoctor doctor) throws Exception{ if(null == doctor || doctor.getId() == null){ throw new HttpStatus401Exception("添加医生失败","DT3388","未知原因","请联系管理员"); } try { System.out.println("成功----------->"+doctor.getName()); } catch (Exception e) { throw new HttpStatus401Exception("添加医生失败","DT3388","未知原因","请联系管理员"); } return doctor.getId().toString(); } /** * 删除医生 * @param doctorId 医生ID * @return */ @ResponseBody @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.DELETE ) @ApiOperation(value="删除医生信息", notes="") @ApiImplicitParam(paramType="query", name = "doctorId", value = "医生ID", required = true, dataType = "Integer") public String deleteDoctor(@RequestParam Integer doctorId){ if(doctorId > 2){ return "删除失败"; } return "删除成功"; } /** * 修改医生信息 * @param doctorId 医生ID * @param doctor 医生信息 * @return * @throws HttpStatus401Exception */ @ResponseBody @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.POST ) @ApiOperation(value="修改医生信息", notes="") @ApiImplicitParam(paramType="query", name = "doctorId", value = "医生ID", required = true, dataType = "Integer") public String updateDoctor(@RequestParam Integer doctorId, @RequestBody DemoDoctor doctor) throws HttpStatus401Exception{ if(null == doctorId || null == doctor){ throw new HttpStatus401Exception("修改医生信息失败","DT3391","id不能为空","请修改"); } if(doctorId > 5 ){ throw new HttpStatus401Exception("医生不存在","DT3392","错误的ID","请更换ID"); } System.out.println(doctorId); System.out.println(doctor); return "修改成功"; } /** * 获取医生详细信息 * @param doctorId 医生ID * @return * @throws HttpStatus401Exception */ @ResponseBody @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.GET ) @ApiOperation(value="获取医生详细信息", notes="仅返回姓名..") @ApiImplicitParam(paramType="query", name = "doctorId", value = "医生ID", required = true, dataType = "Integer") public DemoDoctor getDoctorDetail(@RequestParam Integer doctorId) throws HttpStatus401Exception{ System.out.println(doctorId); if(null == doctorId){ throw new HttpStatus401Exception("查看医生信息失败","DT3390","未知原因","请联系管理员"); } if(doctorId > 3){ throw new HttpStatus401Exception("医生不存在","DT3392","错误的ID","请更换ID"); } DemoDoctor doctor = new DemoDoctor(); doctor.setId(1); doctor.setName("测试员"); return doctor; } /** * 获取医生列表 * @param pageIndex 当前页数 * @param pageSize 每页记录数 * @param request * @return * @throws HttpStatus401Exception */ @ResponseBody @RequestMapping(value="/doctor", method= RequestMethod.GET ) @ApiOperation(value="获取医生列表", notes="目前一次全部取,不分页") @ApiImplicitParams({ @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"), @ApiImplicitParam(paramType="query", name = "pageIndex", value = "当前页数", required = false, dataType = "String"), @ApiImplicitParam(paramType="query", name = "pageSize", value = "每页记录数", required = true, dataType = "String"), }) public PageInfo<DemoDoctor> getDoctorList(@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex, @RequestParam(value = "pageSize", required = false) Integer pageSize, HttpServletRequest request) throws HttpStatus401Exception{ String token = request.getHeader("token"); if(null == token){ throw new HttpStatus401Exception("没有权限","SS8888","没有权限","请查看操作文档"); } if(null == pageSize){ throw new HttpStatus401Exception("每页记录数不粗安在","DT3399","不存在pageSize","请查看操作文档"); } DemoDoctor doctor1 = new DemoDoctor(); doctor1.setId(1); doctor1.setName("测试员1"); DemoDoctor doctor2 = new DemoDoctor(); doctor2.setId(2); doctor2.setName("测试员2"); List<DemoDoctor> doctorList = new ArrayList<DemoDoctor>(); doctorList.add(doctor1); doctorList.add(doctor2); return new PageInfo<DemoDoctor>(doctorList); } }
增加header:
现在很多请求需要在header增加额外参数,可以参考getDoctorList()的做法,使用request接收。
-
Swagger 常用注解使用详解
2018-03-16 09:18:24在集成了swagger2后,找了半天的原因,发现使用@ApiImplicitParam这个注解可以解决这个问题。对应下面的参数。所以我们可以使用这个注解来解决我们所遇到的参考为空的问题。而且已经集成了swagger2,所以我们尽量... -
5分钟了解swagger
2017-08-27 20:47:06API文档变成了前后端开发人员联系的纽带,变得越来越重要,swagger就是一款让你更好的书写API文档的框架。其他API文档工具没有API文档工具之前,大家都是手写API文档的,在什么地方书写的都有,有在confl -
Swagger简介
2015-03-22 21:09:05前言 Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。本文简单介绍了在项目中集成swagger的方法和一些常见问题。...Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视... -
SpringBoot与Swagger2整合
2020-09-23 14:14:59SpringBoot与Swagger整合 依赖: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <... -
-
使用Knife4j美化Swagger
2020-10-15 10:06:46使用Knife4j美化Swagger 依赖: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </... -
-
Swagger 教程
2021-01-02 14:49:26SpringBoot与Swagger2整合 依赖: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> &... -
swagger2 注解说明 ( @ApiImplicitParams )
2018-10-17 12:25:36@Api:用在请求的类上,表示对类的说明 tags="说明该类的作用,可以在UI界面上看到的注解" value="该参数没什么意义,在UI界面上也看到,所以不需要配置" @ApiOperation:用在请求的方法上,说明方法的用途、...
-
基于分层划分的机器人割草机路径规划的双重启发式优化
-
DHCP 动态主机配置服务(在Linux环境下,配置单网段或跨网段提)
-
Circular Linked List in Python
-
上海交通大学819信号系统与信号处理历年考研真题汇编
-
MySQL 主从复制 Replication 详解(Linux 和 W
-
MySQL和JDBC.pdf
-
2021年最新最全图文版的Pi币App下载和注册教程
-
基于改进均值标准差曲线描述子的反射对称轴检测
-
Unity数据读取与写入(Excel,Txt,Xml).rar
-
storygen:基于Tracery的基于语法的文本扩展器-源码
-
【Python-随到随学】 FLask第一周
-
veeam_backup_11_0_user_guide_vsphere.pdf
-
leetcode题解 - 两数之和
-
html2canvas 与 jspdf 相结合生成 pdf 内容被截断问题.txt
-
补体成分C5丨Abbexa小鼠补体C5 ELISA试剂盒
-
Redis 源码学习笔记
-
开发代码流程.pptx
-
ffmpeg-win32-v3.2.4.zip
-
项目经理成长之路
-
“直播系统定制开发怎么样选择专业的软件外包商 “