Springboot引入拦截器并放行swagger代码实例

这篇文章主要介绍了Springboot引入拦截器并放行swagger代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Springboot引入拦截器

自定义的拦截器类 Interceptor

package cn.zytao.taosir.auth.config;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

public class AuthInterceptor implements HandlerInterceptor{

/**

* 请求处理之后

*/

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)

throws Exception {

// TODO Auto-generated method stub

HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

}

/**

* 请求处理之后调用

*/

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,

ModelAndView modelAndView) throws Exception {

// TODO Auto-generated method stub

HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

}

/**

* 请求处理之前

*/

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

throws Exception {

return HandlerInterceptor.super.preHandle(request, response, handler);

}

}

将拦截器添加到springmvc配置中,并放行swagger的相关资源

package cn.zytao.taosir.auth.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration

public class SpringMVCConfig extends WebMvcConfigurationSupport{

@Bean

public AuthInterceptor getAuthInterceptor() {

return new AuthInterceptor();

}

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry

.addInterceptor(getAuthInterceptor())

.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即可,上面主要对此进行了处理。

以上是 Springboot引入拦截器并放行swagger代码实例 的全部内容, 来源链接: utcz.com/z/323515.html

回到顶部