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.trgis.www"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
Contact contact = new Contact("zz", "", "[email protected]");
return new ApiInfoBuilder()
.title("測試")
.description("測試系統API後臺服務接口")
.termsOfServiceUrl("http://www.baidu.com")
.contact(contact)
.version("1.0")
.build();
}
}
3、訪問,IP+端口+doc.html,效果如下
更換swagger-ui
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
訪問:IP+端口+doc.html,效果如下
注:shiro與攔截器取消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" // 用戶登錄
);
}
}