问题:Swagger加入拦截器后swagger-ui.html不显示
在拦截器中添加断点发现请求的URI地址
@Component
public class LoginInterceptor implements HandlerInterceptor {
public static boolean test = true; // 测试模式,关闭登陆验证
@Autowired private ObjectMapper objectMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// if (test) {
// return true;
// }
String requestURI = request.getRequestURI();//在这打断点,查看访问swagger页面的请求路径是什么
if (requestURI.equalsIgnoreCase("/")
|| requestURI.contains("login")
|| requestURI.contains("menus")
|| requestURI.contains("register")
) {
return true;
}
Object user = request.getSession().getAttribute("user");
if (user == null) {
response.setContentType("application/json;charset=utf-8");
response.getWriter()
.write(objectMapper.writeValueAsString(R.setError(ResultCode.NOT_LOGIN, "请登录", null)));
return false;
}
return true;
}
}
首先在springmvc.xml中设置拦截器的放行地址,发现并没有生效,然后将其注释掉
再添加一个配置类,将请求的路径都在这个类中设置放行
@Configuration
public class SpringMvcConfig extends WebMvcConfigurationSupport {
@Bean
public LoginInterceptor getLoginInterceptor() {
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(getLoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
super.addInterceptors(registry);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
在addInterceptors方法中添加拦截器时,是new的一个拦截器。而并不是引入springBean容器初始化时,已经初始化好了的bean实例,并不是同一个对象,故而访问时肯定是无法引入Interceptor类里面引入的bean实例,可能产生空指针异常。
既然无法引入默认注入的Bean,那么我们就自己定义一个Bean,然后在拦截器添加方法内引入这个bean即可,上面主要对此进行了处理。