十二、springboot + gradle整合swagger2(含swagger3)
1、添加依赖implementation 'io.springfox:springfox-swagger2:2.9.2'implementation 'com.github.xiaoymin:swagger-bootstrap-ui:1.8.9'2、写配置文件SwaggerConfigimport org.springframework.context.annotation....
·
一、整合swagger2
1、添加依赖
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'com.github.xiaoymin:swagger-bootstrap-ui:1.8.9'
2、写配置文件SwaggerConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
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 {
@Bean
public Docket createRESTApi() {
//请求时添加head参数start
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.zz.www"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars);
}
private ApiInfo apiInfo() {
Contact contact = new Contact("zz", "", "729253864.@qq.com");
return new ApiInfoBuilder()
.title("测试")
.description("测试系统API后台服务接口")
.termsOfServiceUrl("http://www.baidu.com")
.contact(contact)
.version("1.0")
.build();
}
}
注意:.apis(RequestHandlerSelectors.basePackage("com.zz.www"))里面的com.zz.www改成自己的包名
3、访问,IP+端口+doc.html,效果如下
更换swagger-ui
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
访问:IP+端口+swagger-ui.html,效果如下,controller层加上swwager注解,将会在页面具体显示
代码
@Api(description = "用户登录")
@RestController
public class UserLoginController {
@ApiOperation(value = "登录", notes="登录啊")
@PostMapping("login")
private String login(String account, String password, HttpServletResponse response) {
return null;
}
@ApiOperation(value = "登出", notes="登出啊")
@GetMapping("logout")
private String logout() {
return null;
}
}
不添加注解时如下
注:当项目有拦截器时,需要取消对swagger-ui的访问验证,否则将访问失败
shiro: ShiroConfig中取消验证:
filterMap.put("/swagger-ui.html", "anon");
filterMap.put("/v2/api-docs", "anon");
filterMap.put("/webjars/**", "anon");
filterMap.put("/swagger-resources/**", "anon");
拦截器: 拦截器取消验证
import com.alibaba.fastjson.JSON;
import com.trgis.www.manage.entity.TRUser;
import com.trgis.www.manage.service.TRUserService;
import com.trgis.www.util.BeanUtil;
import com.trgis.www.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
/**
* @Author: zhao
* @CreateDate: 2019/10/17$ 18:57$
*/
@Controller
public class UserTokenInterceptor implements HandlerInterceptor{
@Autowired
private TRUserService trUserService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
TRUser user = (TRUser) session.getAttribute("user");
if (BeanUtil.isEmpty(user)) {
Result result = new Result();
result.setError("登录超时", -1);
returnResult(result, response);
return false;
} else {
Result result = new Result();
String username = user.getUsername();
TRUser trUser = trUserService.findByUsername(username);
if (BeanUtil.isNotEmpty(trUser)) {
if (!trUser.getPassword().equals(user.getPassword())) {
result.setError("用户密码已更改");
returnResult(result, response);
return false;
}
} else {
result.setError("用户不存在");
returnResult(result, response);
return false;
}
}
return true;
}
private void returnResult(Result result, HttpServletResponse response) {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
String json = JSON.toJSONString(result);
try {
writer = response.getWriter();
writer.print(json);
} catch (Exception e) {
} finally {
if (null != writer) {
writer.close();
}
}
}
}
import com.trgis.www.framework.interceptor.UserTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @Author: zhao
* @CreateDate: 2019/10/17$ 18:50$
*/
@Component
public class WebMvcConfig extends WebMvcConfigurationSupport{
@Autowired
private UserTokenInterceptor userTokenInterceptor;
@Override
protected 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/");
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userTokenInterceptor)
.addPathPatterns("/**")
.excludePathPatterns(
"/","/static/**",// 静态资源
"/swagger-ui.html","/v2/api-docs","/webjars/**","/swagger-resources/**", // SwaggerUI
"/login" // 用户登录
);
}
}
二、整合swagger3
1、添加依赖
implementation 'io.springfox:springfox-boot-starter:3.0.0'
2、配置文件application.yml添加
application:
name: lzz
version: 0.0.1
description: 描述
3、添加swagger配置文件,此处已经过滤掉拦截器,后面配置将不必再次配置(遗留问题:项目版本号手动配置,非自动获取以及添加拦截之后页面无法访问)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
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.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.lang.reflect.Field;
import java.util.*;
/**
* @ClassName : SwaggerConfig.java
* @Description : 描述
* @Author : zhangz
* @createTime 2020年07月24日 17:18:00
*/
@Configuration
@EnableOpenApi
public class SwaggerConfig implements WebMvcConfigurer {
@Value("${swagger2.enable}")
private boolean enable;
@Value("${application.name}")
private String applicationName;
@Value("${application.version}")
private String applicationVersion;
@Value("${application.description}")
private String applicationDescription;
@Bean
public Docket createRestApi()
{
return new Docket(DocumentationType.OAS_30).pathMapping("/")
// 定义是否开启swagger,false为关闭,可以通过变量控制
.enable(enable)
// 将api的元信息设置为包含在json ResourceListing响应中。
.apiInfo(apiInfo())
// 选择哪些接口作为swagger的doc发布
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
// 支持的通讯协议集合
.protocols(newHashSet("https", "http"))
// 授权信息设置,必要的header token等认证信息
.securitySchemes(securitySchemes())
// 授权信息全局应用
.securityContexts(securityContexts());
}
/**
* API 页面上半部分展示信息
*/
private ApiInfo apiInfo()
{
return new ApiInfoBuilder().title("Sinhy " + applicationName + " Api Doc")
.description(applicationDescription)
.contact(new Contact("JetLi", null, "zhangz@163.com"))
.version("Application Version: " + applicationVersion + ", Spring Boot Version: " + SpringBootVersion.getVersion())
.build();
}
/**
* 设置授权信息
*/
private List<SecurityScheme> securitySchemes()
{
return Collections.singletonList(new ApiKey("BASE_TOKEN", "token", "pass"));
}
/**
* 授权信息全局应用
*/
private List<SecurityContext> securityContexts()
{
return Collections.singletonList(
SecurityContext.builder().securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[] {new AuthorizationScope("global", "")}))).build());
}
@SafeVarargs
private final <T> Set<T> newHashSet(T... ts)
{
if (ts.length > 0)
{
return new LinkedHashSet<>(Arrays.asList(ts));
}
return null;
}
/**
* 通用拦截器排除swagger设置,所有拦截器都会自动加swagger相关的资源排除信息
*/
@SuppressWarnings("unchecked")
public void addInterceptors(InterceptorRegistry registry)
{
try
{
Field registrationsField = ReflectionUtils.findField(InterceptorRegistry.class, "registrations");
List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
if (registrations != null)
{
for (InterceptorRegistration interceptorRegistration : registrations)
{
interceptorRegistration
.excludePathPatterns("/swagger**/**")
.excludePathPatterns("/webjars/**")
.excludePathPatterns("/v3/**")
.excludePathPatterns("/doc.html");
}
}
}
catch (Exception e)
{
}
}
}
4、访问IP+端口://swagger-ui/index.html 注意此处与swagger2的访问路径不同,效果如下
swagger3的Authorize可全局设置,见下图
更多推荐
已为社区贡献1条内容
所有评论(0)