欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot配置拦截器和资源映射

程序员文章站 2022-06-02 15:14:36
...
  • 创建class类实现org.springframework.web.servlet.HandlerInterceptor
@Slf4j//lombak方便打日志
@Component//注册到spring容器中方便注入
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("前置拦截");
        return true;//根据布尔值设置拦截和放行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("后置拦截");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("最终拦截");
    }
}
  • 创建配置类实现org.springframework.boot.autoconfigure.web.servlet.WebMvcConfigurer 接口
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor myInterceptor;//注入拦截器

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //配置拦截器,并且设置拦截路径
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //设置资源映射 location 用 file://,window用/E:/ww表示资源路径
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:///E:/ww/demos/source/");
    }
}

拦截器和资源映射的最终效果
springboot配置拦截器和资源映射

相关标签: # springboot