说明:本文讲述两种拦截器的实现方法,推荐使用方法二
一:传统实现
1.实现WebMvcConfigurer接口
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器,添加拦截路径和排除拦截路径
registry.addInterceptor(new InterceptorConfig()).addPathPatterns("/**")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**",//前面是方向swagger
"/hello")
;
}
}
2.实现HandlerInterceptor(拦截器实现接口),实现ApplicationContextAware(为了静态工厂注入业务)
@Component public class InterceptorConfig implements HandlerInterceptor, ApplicationContextAware { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { Map<String,String> map = applicationContext.getBean(TestService.class).getAllRoleUrl();//业务接口,判断是否存在可以访问的接口路径 if (map.get(request.getServletPath()) != null) { //response.sendRedirect("/hello");//重定向 return true;//放行 } return false;//拦截 } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } /** * 类似于Spring装载静态工厂 */ private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(this.applicationContext == null) { this.applicationContext = applicationContext; } } }
下面是业务接口:
public interface TestService { Map<String,String> getAllRoleUrl(); }
@Service public class TestServiceImpl implements TestService { public Map<String, String> getAllRoleUrl() { Map<String, String> map = new HashMap<String, String>(); map.put("/saveHello","/saveHello"); map.put("/deleteHello","/deleteHello"); map.put("/getHello","/getHello"); map.put("/updateHello","/updateHello"); return map; } }
二:改造实现(只要一个文件就可以实现拦截器)在标注的地方写业务就行了
@Configuration public class WebAppConfig implements WebMvcConfigurer { @Autowired private TestService testService;//业务代码,查询可以被访问的接口路径 @Override public void addInterceptors(InterceptorRegistry registry) { //注册自定义拦截器,添加拦截路径和排除拦截路径 registry.addInterceptor(new HandlerInterceptor() { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Map<String,String> map = testService.getAllRoleUrl();//业务代码,查询可以被访问的接口路径 if (map.get(request.getServletPath()) != null) { //response.sendRedirect("/hello");//重定向 return true;//放行 } return false;//拦截 } }).addPathPatterns("/**") .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**",//前面是方向swagger "/hello") ; } }
每天提升一点点。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。