简介
API 接口文档。
功能:提供接口,在线测试接口数据。
官网
控制台报错显示多个bean
原版本 swagger2.2.2
解决方案:
升级版本
Failed to start bean ‘documentationPluginsBootstrapper’;
springboot 升级到 2.6.0之后,swagger版本和springboot不兼容。
可能出现Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException报错
解决方案
在启动类 或 配置类 添加注解@EnableWebMvc
我的版本信息
spring boot:2.6.13,swagger:2.9.2
No mapping for GET /emos-wx-api/swagger-ui.html
访问swagger-ui.html控制台报错为:No mapping for GET /emos-wx-api/swagger-ui.html
解决办法:让swagger的配置类SwaggerConfig继承WebMvcConfigurer接口并且实现其中addResourceHandlers方法
具体步骤
简单了解
springboot中配置addResourceHandler作用:读取本地文件
相关链接
Swagger2 的 maven 依赖
<!-- 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>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<scope>compile</scope>
</dependency>
Swagger2 的配置
package com.example.sw.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
@Bean
public Docket createRestApi() {
Docket docket = new Docket(DocumentationType.SWAGGER_2);
//ApiInfoBuilder定义Swagger页面基本信息
ApiInfoBuilder builder = new ApiInfoBuilder();
builder.title("EMOS在线办公系统");
ApiInfo info = builder.build();
docket.apiInfo(info);
//使用ApiSelectorBuilder将Web方法添加到swagger页面
ApiSelectorBuilder selectorBuilder = docket.select();
selectorBuilder.paths(PathSelectors.any());
//加入对应类对应方法具体通过添加注解ApiOperation实现
selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
docket = selectorBuilder.build();
//加入JWT到项目(令牌登录) 实现验证登录成功之后才能调用对应Web方法
ApiKey apiKey = new ApiKey("token", "token", "header");
//List<ApiKey>用户需要输入什么参数 请求提交的参数
List<ApiKey> apiKeyList = new ArrayList<>();
apiKeyList.add(apiKey);
docket.securitySchemes(apiKeyList);
//AuthorizationScope[] JWT认证在Swagger中的作用域
AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] scopes = {scope};
//List<SecurityReference> 令牌的作用域
SecurityReference reference = new SecurityReference("token", scopes);
List refList = new ArrayList();
refList.add(reference);
//List<SecurityContext> 令牌上下文
SecurityContext context = SecurityContext.builder().securityReferences(refList).build();
List cxtList = new ArrayList();
cxtList.add(context);
docket.securityContexts(cxtList);
return docket;
}
}
启动类
添加
package com.example.sw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class SwApplication {
public static void main(String[] args) {
SpringApplication.run(SwApplication.class, args);
}
}
测试
输入
http://localhost:8201/swagger-ui.html
初步尝试
实体类
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "用户实体类")//注解用于类上,表示标识这个类是 swagger 的资源。
public class User {
@ApiModelProperty(value = "用户唯一标识")// 注解用于参数上,用来标明参数信息。
private Integer id;
@ApiModelProperty(value = "用户名")
private String userName;
@ApiModelProperty(value = "密码")
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
controller类
import com.example.db.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
@RestController
@Api(value = "Swagger2 在线接口文档")
public class UserController {
@Resource
private JdbcTemplate jdbcTemplate;
@RequestMapping("/getUserList")
@ApiOperation(value = "获取")
public ArrayList<User> GetUserList(){
String sql = "select * from user";
ArrayList<User> userList = (ArrayList<User>) jdbcTemplate.query(sql,new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUserName(rs.getString("user_name") );
user.setPassword(rs.getString("password"));
return user;
}
});
return userList;
}
@RequestMapping("/setUser")
@ApiOperation(value = "增加")
public String SetUser(@RequestBody User user){
String userName = user.getUserName();
String password = user.getPassword()+ "_cxy";
String sql = "INSERT INTO `user` (`user_name`, `password`) VALUES ('"+userName+"','"+password+"')";
jdbcTemplate.execute(sql);
return "插入成功";
}
@RequestMapping("/updateUser")
@ApiOperation(value = "修改")
public String UpdateUserList(@RequestBody User user){
String userName = user.getUserName();
String password = user.getPassword()+ "_cxy";
String sql = "UPDATE `user` SET `password`='" +
password + "' WHERE (`user_name`='"+userName+"')";
jdbcTemplate.execute(sql);
return "修改成功";
}
@RequestMapping("/deleteUser")
@ApiOperation(value = "根据用户唯一标识获取用户信息")
public String DeleteUserList(@RequestBody User user){
// String userName = user.getUserName();
// String password = user.getPassword();
int id = user.getId();
String sql = "DELETE FROM `user` WHERE (`id` ='"+id+"')";
jdbcTemplate.execute(sql);
return "删除成功";
}
}
测试
TypeError: Failed to execute ‘fetch’ on ‘Window’: Request with GET/HEAD method cannot have body.
这是由于用错请求导致的错误
我测试的 setUser
误用get请求
{
“password”: “1111”,
“userName”: “王八蛋”
}
但是
在HTTP协议中,GET 请求通常用于请求数据,而 POST、PUT、PATCH 等请求方法则用于提交数据。
GET 请求本身并不包含请求体(request body),而是将需要传输的数据附加在URL的查询字符串(query string)中。
由于 GET 请求没有请求体,所以自然就没有 RequestBody 的概念。
换成post请求即可
参考资料
https://blog.csdn.net/weixin_45131680/article/details/131580270
https://github.com/spring-projects/spring-framework/blob/main/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java
https://blog.csdn.net/apple_51673523/article/details/125944572