swagger用于定义API文档。
Swagger2的使用
Maven Plugin添加Swagger2相关jar包
![](https://yqfile.alicdn.com/img_1c53668bcee393edac0d7b3b3daff1ae.gif?x-oss-process=image/resize,w_1400/format,webp)
![](https://yqfile.alicdn.com/img_405b18b4b6584ae338e0f6ecaf736533.gif?x-oss-process=image/resize,w_1400/format,webp)
1 <!--swagger2 start--> 2 <dependency> 3 <groupId>io.springfox</groupId> 4 <artifactId>springfox-swagger2</artifactId> 5 <version>2.2.2</version> 6 </dependency> 7 <dependency> 8 <groupId>io.springfox</groupId> 9 <artifactId>springfox-swagger-ui</artifactId> 10 <version>2.2.2</version> 11 </dependency> 12 <!--swagger2 end-->
添加Swagger2配置文件
![](https://yqfile.alicdn.com/img_1c53668bcee393edac0d7b3b3daff1ae.gif?x-oss-process=image/resize,w_1400/format,webp)
![](https://yqfile.alicdn.com/img_405b18b4b6584ae338e0f6ecaf736533.gif?x-oss-process=image/resize,w_1400/format,webp)
1 package com.goku.webapi.config.Swagger; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 import springfox.documentation.builders.ApiInfoBuilder; 6 import springfox.documentation.builders.PathSelectors; 7 import springfox.documentation.builders.RequestHandlerSelectors; 8 import springfox.documentation.service.ApiInfo; 9 import springfox.documentation.spi.DocumentationType; 10 import springfox.documentation.spring.web.plugins.Docket; 11 import springfox.documentation.swagger2.annotations.EnableSwagger2; 12 13 /** 14 * Created by nbfujx on 2017-11-14. 15 */ 16 @Configuration 17 @EnableSwagger2 18 public class Swagger2Config { 19 20 @Bean 21 public Docket createRestApi() { 22 return new Docket(DocumentationType.SWAGGER_2) 23 .apiInfo(apiInfo()) 24 .select() 25 .apis(RequestHandlerSelectors.basePackage("com.goku.webapi.controller")) 26 .paths(PathSelectors.any()) 27 .build(); 28 } 29 30 private ApiInfo apiInfo() { 31 return new ApiInfoBuilder() 32 .title("Goku.WebService.Simple") 33 .description("Goku.WebService.Simple") 34 .termsOfServiceUrl("https://github.com/nbfujx") 35 .contact("nbfujx") 36 .version("1.0") 37 .build(); 38 } 39 }
添加文档内容
在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过
@ApiOperation
注解来给API增加说明、通过
@ApiImplicitParams
、
@ApiImplicitParam
注解来给参数增加说明。同时可以使用
@ApiIgnore来过滤一些不需要展示的接口。
![](https://yqfile.alicdn.com/img_1c53668bcee393edac0d7b3b3daff1ae.gif?x-oss-process=image/resize,w_1400/format,webp)
![](https://yqfile.alicdn.com/img_405b18b4b6584ae338e0f6ecaf736533.gif?x-oss-process=image/resize,w_1400/format,webp)
1 package com.goku.webapi.controller.impl; 2 3 import com.alibaba.fastjson.JSON; 4 import com.goku.webapi.controller.loginController; 5 import com.goku.webapi.util.enums.returnCode; 6 import com.goku.webapi.util.message.returnMsg; 7 import io.swagger.annotations.Api; 8 import io.swagger.annotations.ApiImplicitParam; 9 import io.swagger.annotations.ApiImplicitParams; 10 import io.swagger.annotations.ApiOperation; 11 import org.apache.shiro.SecurityUtils; 12 import org.apache.shiro.authc.AuthenticationException; 13 import org.apache.shiro.authc.UsernamePasswordToken; 14 import org.apache.shiro.crypto.hash.Md5Hash; 15 import org.apache.shiro.session.SessionException; 16 import org.apache.shiro.subject.Subject; 17 import org.springframework.beans.factory.annotation.Autowired; 18 import org.springframework.boot.autoconfigure.web.ErrorAttributes; 19 import org.springframework.boot.autoconfigure.web.ErrorController; 20 import org.springframework.http.HttpStatus; 21 import org.springframework.web.bind.annotation.RequestMapping; 22 import org.springframework.web.bind.annotation.RequestMethod; 23 import org.springframework.web.bind.annotation.RequestParam; 24 import org.springframework.web.bind.annotation.RestController; 25 import org.springframework.web.context.request.RequestAttributes; 26 import org.springframework.web.context.request.ServletRequestAttributes; 27 import springfox.documentation.annotations.ApiIgnore; 28 29 import javax.servlet.http.HttpServletRequest; 30 import java.util.HashMap; 31 import java.util.Map; 32 33 34 /** 35 * Created by nbfujx on 2017-11-07. 36 */ 37 @RestController 38 @Api(value="登录验证") 39 public class loginControllerImpl implements loginController,ErrorController { 40 41 42 private final static String ERROR_PATH = "/error"; 43 44 @Autowired 45 private ErrorAttributes errorAttributes; 46 47 @ApiOperation(value="用户登录", notes="用户登录校验") 48 @ApiImplicitParams({ 49 @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String" ,paramType="query"), 50 @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String" ,paramType="query"), 51 @ApiImplicitParam(name = "rememberMe", value = "记住用户", required = true, dataType = "String" ,paramType="query") 52 }) 53 @RequestMapping(value = "/login", method = RequestMethod.POST) 54 public String login( 55 @RequestParam(value = "username", required = true) String userName, 56 @RequestParam(value = "password", required = true) String password, 57 @RequestParam(value = "rememberMe", required = true, defaultValue = "false") boolean rememberMe 58 ) { 59 String passwordmd5 = new Md5Hash(password, "2").toString(); 60 Subject subject = SecurityUtils.getSubject(); 61 UsernamePasswordToken token = new UsernamePasswordToken(userName, passwordmd5); 62 token.setRememberMe(rememberMe); 63 try { 64 subject.login(token); 65 } catch (AuthenticationException e) { 66 e.printStackTrace(); 67 return JSON.toJSONString (new returnMsg(returnCode.ERROR)); 68 } 69 return JSON.toJSONString (new returnMsg(returnCode.SUCCESS)); 70 } 71 72 73 @Override 74 @RequestMapping(value = "/logout", method = RequestMethod.POST) 75 @ApiOperation(value="用户退出", notes="用户退出校验") 76 public String logout() { 77 Subject subject = SecurityUtils.getSubject(); 78 try { 79 subject.logout(); 80 }catch (SessionException e){ 81 e.printStackTrace(); 82 return JSON.toJSONString (new returnMsg(returnCode.ERROR)); 83 } 84 return JSON.toJSONString (new returnMsg(returnCode.SUCCESS)); 85 } 86 87 @Override 88 @RequestMapping(value = "/notAuthc", method = RequestMethod.GET) 89 @ApiIgnore 90 public String notAuthc() { 91 return JSON.toJSONString (new returnMsg(returnCode.NOTAUTHC)); 92 } 93 94 @Override 95 @RequestMapping(value = "/notAuthz", method = RequestMethod.GET) 96 @ApiIgnore 97 public String notAuthz() { 98 return JSON.toJSONString (new returnMsg(returnCode.NOTAUTHZ)); 99 } 100 101 @Override 102 @RequestMapping(value =ERROR_PATH) 103 @ApiIgnore 104 public String error(HttpServletRequest request) 105 { 106 Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request)); 107 return JSON.toJSONString (new returnMsg(returnCode.ERROR,body)); 108 } 109 110 @Override 111 public String getErrorPath() { 112 return ERROR_PATH; 113 } 114 115 private boolean getTraceParameter(HttpServletRequest request) { 116 String parameter = request.getParameter("trace"); 117 if (parameter == null) { 118 return false; 119 } 120 return !"false".equals(parameter.toLowerCase()); 121 } 122 123 private Map<String, Object> getErrorAttributes(HttpServletRequest request,boolean includeStackTrace) { 124 RequestAttributes requestAttributes = new ServletRequestAttributes(request); 125 Map<String, Object> map = this.errorAttributes.getErrorAttributes(requestAttributes,includeStackTrace); 126 String URL = request.getRequestURL().toString(); 127 map.put("URL", URL); 128 return map; 129 } 130 131 }
完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html
注解说明:
- @Api:用在类上,说明该类的作用
- @ApiOperation:用在方法上,说明方法的作用
- @ApiImplicitParams:用在方法上包含一组参数说明
- @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
- paramType:参数放在哪个地方
- header-->请求参数的获取:@RequestHeader
- query-->请求参数的获取:@RequestParam
- path(用于restful接口)-->请求参数的获取:@PathVariable
- body(不常用)
- form(不常用)
- name:参数名
- dataType:参数类型
- required:参数是否必须传
- value:参数的意思
- defaultValue:参数的默认值
- paramType:参数放在哪个地方
- @ApiResponses:用于表示一组响应
- @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
- code:数字,例如400
- message:信息,例如"请求参数没填好"
- response:抛出异常的类
- @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
- @ApiModelProperty:描述一个model的属性
GITHUB
github : https://github.com/nbfujx/learn-java-demo/tree/master/Goku.WebService.Simple.Swagger2