swagger


  实际项目中非常需要写文档,提高Java服务端和Web前端以及移动端的对接效率。
  听说Swagger这个工具,还不错,就网上找了些资料,自己实践了下。

一:Swagger介绍

Swagger是当前最好用的Restful API文档生成的开源项目,通过swagger-spring项目

实现了与SpingMVC框架的无缝集成功能,方便生成spring restful风格的接口文档,

同时swagger-ui还可以测试spring restful风格的接口功能。


官方网站为:http://swagger.io/


中文网站:http://www.sosoapi.com


二:Swagger与Spring MVC集成步骤

1.Maven关键配置

        

  
  
  1. <dependency>
  2. <groupId>com.mangofactory </groupId>
  3. <artifactId>swagger-springmvc </artifactId>
  4. <version>1.0.2 </version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework </groupId>
  8. <artifactId>spring-webmvc </artifactId>
  9. <version>4.1.6.RELEASE </version>
  10. </dependency>


2. 插件配置
   CustomJavaPluginConfig

3.复制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:
   

   
   
  1. @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  2. @ResponseBody
  3. @RequestMapping(value = "list", method = RequestMethod.POST)
  4. public Result<User> list(
  5. @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId,
  6. @ApiParam(value = "token", required = true) @RequestParam String token) {
  7. Result<User> result = new Result<User>();
  8. User user = new User();
  9. result.setData(user);
  10. return result;
  11. }


   @ApiParam(value = "token", required = true) @RequestParam String token
Web前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。

  例子2:

  
  
  1. @ApiOperation(value = "update用户", notes = ")", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  2. @ResponseBody
  3. @RequestMapping(value = "update", method = RequestMethod.GET /*,produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE*/)
  4. public Result<String> update(User user) {
  5. String u = findUser(user);
  6. System.out.println(u);
  7. return null;
  8. }


 当参数太多的时候,需要定义太多的参数,排版看起来很不舒服。
这个时候,可以使用对象来接收。
@ApiModel(value = "用户对象",description="user2") 
public class User extends CommonParam{

}
Web前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。
这里面存在一个小问题,当后端用对象User来接收参数的时候,Swagger自带的工具是这样的:
 
这种形式,并不是表单提交,或者把参数附加到URL的后面。
我们只能手动构造URL,附带参数去提交。
如果需要测试的话!

例子3:

   
   
  1. public Result<String> add(@RequestBody User user) {
  2. String u = findUser(user);
  3. System.out.println(u);
  4. return null;
  5. }


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,不通用,局限性比较大。


五、若干截图
 

六、源代码

   
   
  1. package cn.fansunion.swagger.serverapi.controller;
  2. import org.springframework.http.MediaType;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestBody;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import org.springframework.web.bind.annotation.RequestParam;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import com.wordnik.swagger.annotations.Api;
  10. import com.wordnik.swagger.annotations.ApiOperation;
  11. import com.wordnik.swagger.annotations.ApiParam;
  12. /**
  13. * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119
  14. * 博客:http://blog.csdn.net/fansunion
  15. *
  16. */
  17. @Api(value = "user", description = "用户管理", produces = MediaType.APPLICATION_JSON_VALUE)
  18. @Controller
  19. @RequestMapping( "user")
  20. public class UserController {
  21. // 列出某个类目的所有规格
  22. @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  23. @ResponseBody
  24. @RequestMapping(value = "list", method = RequestMethod.POST)
  25. public Result<User> list(
  26. @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId,
  27. @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId2,
  28. @ApiParam(value = "token", required = true) @RequestParam String token) {
  29. Result<User> result = new Result<User>();
  30. User user = new User();
  31. result.setData(user);
  32. return result;
  33. }
  34. @ApiOperation(value = "添加用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  35. @ResponseBody
  36. @RequestMapping(value = "add", method = RequestMethod.POST)
  37. // @RequestBody只能有1个
  38. // 使用了@RequestBody,不能在拦截器中,获得流中的数据,再json转换,拦截器中,也不清楚数据的类型,无法转换成java对象
  39. // 只能手动调用方法
  40. public Result<String> add(@RequestBody User user) {
  41. String u = findUser(user);
  42. System.out.println(u);
  43. return null;
  44. }
  45. @ApiOperation(value = "update用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  46. @ResponseBody
  47. @RequestMapping(value = "update", method = RequestMethod.GET)
  48. public Result<String> update(User user) {
  49. String u = findUser(user);
  50. System.out.println(u);
  51. return null;
  52. }
  53. private String findUser(User user) {
  54. String token = user.getToken();
  55. return token;
  56. }
  57. }



   
   
  1. package cn.fansunion.swagger.serverapi.controller;
  2. import com.wordnik.swagger.annotations.ApiModel;
  3. import com.wordnik.swagger.annotations.ApiModelProperty;
  4. /**
  5. * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119
  6. * 博客:http://blog.csdn.net/fansunion
  7. *
  8. */
  9. @ApiModel(value = "用户对象", description = "user2")
  10. public class User extends CommonParam {
  11. @ApiModelProperty(value = "商品信息", required = true)
  12. private String name;
  13. @ApiModelProperty(value = "密码", required = true)
  14. private String password;
  15. @ApiModelProperty(value = "性别")
  16. private Integer sex;
  17. @ApiModelProperty(value = "密码", required = true)
  18. private String token;
  19. public String getToken() {
  20. return token;
  21. }
  22. public void setToken(String token) {
  23. this.token = token;
  24. }
  25. public String getName() {
  26. return name;
  27. }
  28. public void setName(String name) {
  29. this.name = name;
  30. }
  31. public String getPassword() {
  32. return password;
  33. }
  34. public void setPassword(String password) {
  35. this.password = password;
  36. }
  37. public Integer getSex() {
  38. return sex;
  39. }
  40. public void setSex(Integer sex) {
  41. this.sex = sex;
  42. }
  43. }


   
   
  1. package cn.fansunion.swagger.serverapi.swagger;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
  6. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  8. import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
  9. import com.mangofactory.swagger.models.dto.ApiInfo;
  10. import com.mangofactory.swagger.paths.SwaggerPathProvider;
  11. import com.mangofactory.swagger.plugin.EnableSwagger;
  12. import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
  13. @Configuration
  14. @EnableWebMvc
  15. @EnableSwagger
  16. public class CustomJavaPluginConfig extends WebMvcConfigurerAdapter {
  17. private SpringSwaggerConfig springSwaggerConfig;
  18. @Autowired
  19. public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
  20. this.springSwaggerConfig = springSwaggerConfig;
  21. }
  22. /**
  23. * 链式编程 来定制API样式 后续会加上分组信息
  24. *
  25. * @return
  26. */
  27. @Bean
  28. public SwaggerSpringMvcPlugin customImplementation() {
  29. return new SwaggerSpringMvcPlugin( this.springSwaggerConfig)
  30. .apiInfo(apiInfo()).includePatterns( ".*")
  31. .useDefaultResponseMessages( false)
  32. // .pathProvider(new GtPaths())
  33. .apiVersion( "0.1").swaggerGroup( "user");
  34. }
  35. private ApiInfo apiInfo() {
  36. ApiInfo apiInfo = new ApiInfo( "小雷移动端API接口平台",
  37. "提供详细的后台所有Restful接口", "http://blog.csdn.net/FansUnion",
  38. "FansUnion@qq.com", "小雷博客", "http://blog.csdn.net/FansUnion");
  39. return apiInfo;
  40. }
  41. @Override
  42. public void configureDefaultServletHandling(
  43. DefaultServletHandlerConfigurer configurer) {
  44. configurer.enable();
  45. }
  46. class GtPaths extends SwaggerPathProvider {
  47. @Override
  48. protected String applicationPath() {
  49. return "/restapi";
  50. }
  51. @Override
  52. protected String getDocumentationPath() {
  53. return "/restapi";
  54. }
  55. }
  56. }

七、项目下载地址

八、参考资料

  实际项目中非常需要写文档,提高Java服务端和Web前端以及移动端的对接效率。
  听说Swagger这个工具,还不错,就网上找了些资料,自己实践了下。

一:Swagger介绍

Swagger是当前最好用的Restful API文档生成的开源项目,通过swagger-spring项目

实现了与SpingMVC框架的无缝集成功能,方便生成spring restful风格的接口文档,

同时swagger-ui还可以测试spring restful风格的接口功能。


官方网站为:http://swagger.io/


中文网站:http://www.sosoapi.com


二:Swagger与Spring MVC集成步骤

1.Maven关键配置

        

  
  
  1. <dependency>
  2. <groupId>com.mangofactory </groupId>
  3. <artifactId>swagger-springmvc </artifactId>
  4. <version>1.0.2 </version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework </groupId>
  8. <artifactId>spring-webmvc </artifactId>
  9. <version>4.1.6.RELEASE </version>
  10. </dependency>


2. 插件配置
   CustomJavaPluginConfig

3.复制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:
   

   
   
  1. @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  2. @ResponseBody
  3. @RequestMapping(value = "list", method = RequestMethod.POST)
  4. public Result<User> list(
  5. @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId,
  6. @ApiParam(value = "token", required = true) @RequestParam String token) {
  7. Result<User> result = new Result<User>();
  8. User user = new User();
  9. result.setData(user);
  10. return result;
  11. }


   @ApiParam(value = "token", required = true) @RequestParam String token
Web前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。

  例子2:

  
  
  1. @ApiOperation(value = "update用户", notes = ")", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  2. @ResponseBody
  3. @RequestMapping(value = "update", method = RequestMethod.GET /*,produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE*/)
  4. public Result<String> update(User user) {
  5. String u = findUser(user);
  6. System.out.println(u);
  7. return null;
  8. }


 当参数太多的时候,需要定义太多的参数,排版看起来很不舒服。
这个时候,可以使用对象来接收。
@ApiModel(value = "用户对象",description="user2") 
public class User extends CommonParam{

}
Web前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。
这里面存在一个小问题,当后端用对象User来接收参数的时候,Swagger自带的工具是这样的:
 
这种形式,并不是表单提交,或者把参数附加到URL的后面。
我们只能手动构造URL,附带参数去提交。
如果需要测试的话!

例子3:

   
   
  1. public Result<String> add(@RequestBody User user) {
  2. String u = findUser(user);
  3. System.out.println(u);
  4. return null;
  5. }


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,不通用,局限性比较大。


五、若干截图
 

六、源代码

   
   
  1. package cn.fansunion.swagger.serverapi.controller;
  2. import org.springframework.http.MediaType;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestBody;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import org.springframework.web.bind.annotation.RequestParam;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import com.wordnik.swagger.annotations.Api;
  10. import com.wordnik.swagger.annotations.ApiOperation;
  11. import com.wordnik.swagger.annotations.ApiParam;
  12. /**
  13. * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119
  14. * 博客:http://blog.csdn.net/fansunion
  15. *
  16. */
  17. @Api(value = "user", description = "用户管理", produces = MediaType.APPLICATION_JSON_VALUE)
  18. @Controller
  19. @RequestMapping( "user")
  20. public class UserController {
  21. // 列出某个类目的所有规格
  22. @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  23. @ResponseBody
  24. @RequestMapping(value = "list", method = RequestMethod.POST)
  25. public Result<User> list(
  26. @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId,
  27. @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId2,
  28. @ApiParam(value = "token", required = true) @RequestParam String token) {
  29. Result<User> result = new Result<User>();
  30. User user = new User();
  31. result.setData(user);
  32. return result;
  33. }
  34. @ApiOperation(value = "添加用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  35. @ResponseBody
  36. @RequestMapping(value = "add", method = RequestMethod.POST)
  37. // @RequestBody只能有1个
  38. // 使用了@RequestBody,不能在拦截器中,获得流中的数据,再json转换,拦截器中,也不清楚数据的类型,无法转换成java对象
  39. // 只能手动调用方法
  40. public Result<String> add(@RequestBody User user) {
  41. String u = findUser(user);
  42. System.out.println(u);
  43. return null;
  44. }
  45. @ApiOperation(value = "update用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
  46. @ResponseBody
  47. @RequestMapping(value = "update", method = RequestMethod.GET)
  48. public Result<String> update(User user) {
  49. String u = findUser(user);
  50. System.out.println(u);
  51. return null;
  52. }
  53. private String findUser(User user) {
  54. String token = user.getToken();
  55. return token;
  56. }
  57. }



   
   
  1. package cn.fansunion.swagger.serverapi.controller;
  2. import com.wordnik.swagger.annotations.ApiModel;
  3. import com.wordnik.swagger.annotations.ApiModelProperty;
  4. /**
  5. * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119
  6. * 博客:http://blog.csdn.net/fansunion
  7. *
  8. */
  9. @ApiModel(value = "用户对象", description = "user2")
  10. public class User extends CommonParam {
  11. @ApiModelProperty(value = "商品信息", required = true)
  12. private String name;
  13. @ApiModelProperty(value = "密码", required = true)
  14. private String password;
  15. @ApiModelProperty(value = "性别")
  16. private Integer sex;
  17. @ApiModelProperty(value = "密码", required = true)
  18. private String token;
  19. public String getToken() {
  20. return token;
  21. }
  22. public void setToken(String token) {
  23. this.token = token;
  24. }
  25. public String getName() {
  26. return name;
  27. }
  28. public void setName(String name) {
  29. this.name = name;
  30. }
  31. public String getPassword() {
  32. return password;
  33. }
  34. public void setPassword(String password) {
  35. this.password = password;
  36. }
  37. public Integer getSex() {
  38. return sex;
  39. }
  40. public void setSex(Integer sex) {
  41. this.sex = sex;
  42. }
  43. }


   
   
  1. package cn.fansunion.swagger.serverapi.swagger;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
  6. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  8. import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
  9. import com.mangofactory.swagger.models.dto.ApiInfo;
  10. import com.mangofactory.swagger.paths.SwaggerPathProvider;
  11. import com.mangofactory.swagger.plugin.EnableSwagger;
  12. import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
  13. @Configuration
  14. @EnableWebMvc
  15. @EnableSwagger
  16. public class CustomJavaPluginConfig extends WebMvcConfigurerAdapter {
  17. private SpringSwaggerConfig springSwaggerConfig;
  18. @Autowired
  19. public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
  20. this.springSwaggerConfig = springSwaggerConfig;
  21. }
  22. /**
  23. * 链式编程 来定制API样式 后续会加上分组信息
  24. *
  25. * @return
  26. */
  27. @Bean
  28. public SwaggerSpringMvcPlugin customImplementation() {
  29. return new SwaggerSpringMvcPlugin( this.springSwaggerConfig)
  30. .apiInfo(apiInfo()).includePatterns( ".*")
  31. .useDefaultResponseMessages( false)
  32. // .pathProvider(new GtPaths())
  33. .apiVersion( "0.1").swaggerGroup( "user");
  34. }
  35. private ApiInfo apiInfo() {
  36. ApiInfo apiInfo = new ApiInfo( "小雷移动端API接口平台",
  37. "提供详细的后台所有Restful接口", "http://blog.csdn.net/FansUnion",
  38. "FansUnion@qq.com", "小雷博客", "http://blog.csdn.net/FansUnion");
  39. return apiInfo;
  40. }
  41. @Override
  42. public void configureDefaultServletHandling(
  43. DefaultServletHandlerConfigurer configurer) {
  44. configurer.enable();
  45. }
  46. class GtPaths extends SwaggerPathProvider {
  47. @Override
  48. protected String applicationPath() {
  49. return "/restapi";
  50. }
  51. @Override
  52. protected String getDocumentationPath() {
  53. return "/restapi";
  54. }
  55. }
  56. }

七、项目下载地址

八、参考资料
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值