knife4j官方文档地址
之前经常使用swagger2来调试接口,听神仙朋友介绍 knife4j 比较好用。今天试着使用了下。感觉还不错。这里记录下,方便今后学习使用。
这里是使用添加cookies方式测试,post,get,上传文件测试
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<!--在引用时请在maven中央仓库搜索最新版本号-->
<version>2.0.2</version>
</dependency>
spring.application.name=knife4j
server.port=2080
package com.zjy.knife4j.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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
@EnableKnife4j
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zjy.knife4j.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger-bootstrap-ui RESTful APIs")
.description("swagger-bootstrap-ui")
.termsOfServiceUrl("http://localhost:8999/")
.version("1.0")
.build();
}
}
package com.zjy.knife4j.controller;
import com.zjy.knife4j.model.ResultBO;
import com.zjy.knife4j.model.User;
import com.zjy.knife4j.utils.CookieUtils;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;
@RequestMapping("/user")
@RestController
public class UserController {
/**日志对象*/
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@ApiOperation(value = "用户登录测试接口", notes = "用户登录试接口000")
@PostMapping("login")
public ResultBO<User> login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response){
logger.info("传入的user对象为:{}", user);
ResultBO results = new ResultBO();
String cookieName = UUID.randomUUID().toString();
Cookie cookie = new Cookie("ss_at", cookieName);
logger.info("生成的 cookie 对象为:{}, cookies 为:{}", cookie, cookieName);
response.addCookie(cookie);
results.setCode(200);
results.setContent(cookieName);
results.setMsg("调用测试接口成功!");
results.setSucceed(true);
logger.info("调用测试接口成功");
return results;
}
@ApiImplicitParams({
@ApiImplicitParam(name = "name",value = "用户名称", required = true, dataType = "String", paramType = "path", example = "默认值")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "接口返回成功状态!"),
@ApiResponse(code = 500, message = "接口返回未知错误!")
})
@ApiOperation(value = "查询测试接口", notes = "查询测试接口1111")
@GetMapping("getUser/{name}/{message}")
public ResultBO<User> getUser(@PathVariable String name, @PathVariable String message, HttpServletRequest request){
logger.info("传入的name为:{}, 传入的message为:{}", name, message);
logger.info("传入的request为:{}", request);
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest httpServletRequest = attributes.getRequest();
String accessToken = CookieUtils.getCookieValue(httpServletRequest, "ss_at");
logger.info("获取到的accessToken为:{}", accessToken);
ResultBO results = new ResultBO();
User user = new User();
user.setName(name);
user.setMessage(message);
results.setCode(200);
results.setContent(user);
results.setMsg("调用测试接口成功!");
results.setSucceed(true);
logger.info("调用测试接口成功");
return results;
}
@ApiOperation(value = "保存测试接口", notes = "保存测试接口222")
@PostMapping("saveUser")
public ResultBO<User> saveUser(@RequestBody User user){
logger.info("传入的user对象为:{}", user);
ResultBO results = new ResultBO();
results.setCode(200);
results.setContent(user);
results.setMsg("调用测试接口成功!");
results.setSucceed(true);
logger.info("调用测试接口成功");
return results;
}
@ApiOperation(value = "上传测试接口", notes = "上传测试接口333")
@PostMapping("upload")
public ResultBO<User> upload(@RequestParam("file") List<MultipartFile> uploadFiles){
logger.info("传入的uploadFiles对象集合为:{}", uploadFiles);
ResultBO results = new ResultBO();
results.setCode(200);
results.setMsg("调用测试接口成功!");
results.setSucceed(true);
logger.info("调用测试接口成功");
return results;
}
}
package com.zjy.knife4j.model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class ResultBO<T> {
@ApiModelProperty(required = true, notes = "返回数据")
private T content;
@ApiModelProperty(required = true, notes = "返回成功与否", example = "true")
private boolean succeed = true;
@ApiModelProperty(required = true, notes = "结果码", example = "200")
private int code = 0;
@ApiModelProperty(required = true, notes = "返回信息说明", example = "SUCCESS")
private String msg;
public ResultBO(T content) {
this.content = content;
}
public ResultBO(boolean succeed, int code, String msg, T content) {
this.succeed = succeed;
this.code = code;
this.msg = msg;
this.content = content;
}
public ResultBO(boolean succeed, int code, String msg) {
this.succeed = succeed;
this.code = code;
this.msg = msg;
}
public ResultBO() {
}
public static <T> ResultBO<T> success(T content) {
return new ResultBO<T>(content);
}
public static ResultBO success() {
return new ResultBO();
}
public static ResultBO fail(int code, String msg) {
return new ResultBO(false, code, msg);
}
public static ResultBO fail(String msg) {
return new ResultBO(false, -1, msg);
}
public static ResultBO fail() {
return fail("fail");
}
}
package com.zjy.knife4j.model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class User {
@ApiModelProperty(required = true, notes = "用户名", example = "入参用户名")
private String name;
@ApiModelProperty(required = true, notes = "入参信息", example = "入参信息")
private String message;
}
package com.zjy.knife4j.utils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
/**
* cookie工具类
*/
public class CookieUtils {
public static Cookie getCookie(HttpServletRequest request, String cookieName){
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
try{
if (cookies != null && cookies.length > 0){
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(cookieName)){
return cookies[i];
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return cookie;
}
public static String getCookieValue(HttpServletRequest request, String cookieName){
Cookie cookie = getCookie(request,cookieName);
if (cookie != null){
return cookie.getValue();
}else {
return null;
}
}
public static Cookie getCookie(Cookie[] cookies, String cookieName) {
if (null == cookies) {
return null;
} else {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
return cookie;
}
}
return null;
}
}
}
项目启动后。访问:http://localhost:2080/doc.html#/
+++++++++++++++++
添加一个cookies测试。结果发现测试有问题。cookies没有传到后台。不知道哪里有问题。知道的大佬留言告诉一下。万分感谢!
传入的cookies没有接到。不知道哪里出了问题了。郁闷!!!
+++++++++++++++++
测试OK
测试OK!
下载的这一堆乱码再熟悉不过了,浏览器直接访问地址:http://localhost:2080/user/download?path=D:/xm/image/花生米.png 链接是可以下载的
就是本地图片再下载到本地。
测试OK!
欢迎大神指导,可以留言交流!
======================
本人原创文章,转载注明出入!
=================