swagger用于定义API文档。
Swagger2的使用
Maven Plugin添加Swagger2相关jar包
<!--swagger2 start-->
<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>
<!--swagger2 end-->
添加Swagger2配置文件
package com.goku.webapi.config.Swagger; 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; /**
* Created by nbfujx on 2017-11-14.
*/
@Configuration
@EnableSwagger2
public class Swagger2Config { @Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.goku.webapi.controller"))
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Goku.WebService.Simple")
.description("Goku.WebService.Simple")
.termsOfServiceUrl("https://github.com/nbfujx")
.contact("nbfujx")
.version("1.0")
.build();
}
}
添加文档内容
在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过
@ApiOperation
注解来给API增加说明、通过@ApiImplicitParams
、@ApiImplicitParam
注解来给参数增加说明。同时可以使用@ApiIgnore来过滤一些不需要展示的接口。package com.goku.webapi.controller.impl; import com.alibaba.fastjson.JSON;
import com.goku.webapi.controller.loginController;
import com.goku.webapi.util.enums.returnCode;
import com.goku.webapi.util.message.returnMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
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.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import springfox.documentation.annotations.ApiIgnore; import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map; /**
* Created by nbfujx on 2017-11-07.
*/
@RestController
@Api(value="登录验证")
public class loginControllerImpl implements loginController,ErrorController { private final static String ERROR_PATH = "/error"; @Autowired
private ErrorAttributes errorAttributes; @ApiOperation(value="用户登录", notes="用户登录校验")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String" ,paramType="query"),
@ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String" ,paramType="query"),
@ApiImplicitParam(name = "rememberMe", value = "记住用户", required = true, dataType = "String" ,paramType="query")
})
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(
@RequestParam(value = "username", required = true) String userName,
@RequestParam(value = "password", required = true) String password,
@RequestParam(value = "rememberMe", required = true, defaultValue = "false") boolean rememberMe
) {
String passwordmd5 = new Md5Hash(password, "2").toString();
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userName, passwordmd5);
token.setRememberMe(rememberMe);
try {
subject.login(token);
} catch (AuthenticationException e) {
e.printStackTrace();
return JSON.toJSONString (new returnMsg(returnCode.ERROR));
}
return JSON.toJSONString (new returnMsg(returnCode.SUCCESS));
} @Override
@RequestMapping(value = "/logout", method = RequestMethod.POST)
@ApiOperation(value="用户退出", notes="用户退出校验")
public String logout() {
Subject subject = SecurityUtils.getSubject();
try {
subject.logout();
}catch (SessionException e){
e.printStackTrace();
return JSON.toJSONString (new returnMsg(returnCode.ERROR));
}
return JSON.toJSONString (new returnMsg(returnCode.SUCCESS));
} @Override
@RequestMapping(value = "/notAuthc", method = RequestMethod.GET)
@ApiIgnore
public String notAuthc() {
return JSON.toJSONString (new returnMsg(returnCode.NOTAUTHC));
} @Override
@RequestMapping(value = "/notAuthz", method = RequestMethod.GET)
@ApiIgnore
public String notAuthz() {
return JSON.toJSONString (new returnMsg(returnCode.NOTAUTHZ));
} @Override
@RequestMapping(value =ERROR_PATH)
@ApiIgnore
public String error(HttpServletRequest request)
{
Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request));
return JSON.toJSONString (new returnMsg(returnCode.ERROR,body));
} @Override
public String getErrorPath() {
return ERROR_PATH;
} private boolean getTraceParameter(HttpServletRequest request) {
String parameter = request.getParameter("trace");
if (parameter == null) {
return false;
}
return !"false".equals(parameter.toLowerCase());
} private Map<String, Object> getErrorAttributes(HttpServletRequest request,boolean includeStackTrace) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
Map<String, Object> map = this.errorAttributes.getErrorAttributes(requestAttributes,includeStackTrace);
String URL = request.getRequestURL().toString();
map.put("URL", URL);
return map;
} }
完成上述代码添加上,启动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