springboot自定义拦截器

目录

1介绍2springboot初体验3springboot集成jsp4springboot属性注入5springboot集成mybatis6springboot集成lombok7springboot集成logback日志8springboot开启全局热部署9springboot面向切面编程10springboot文件上传11springboot文件下载12springboot自定义拦截器13springboot打成war包发布14springboot打成jar包发布15springboot自定义banner16springboot配置文件拆分

拦截器介绍

特点
  1. 请求到达会经过拦截器,响应回来还要经过拦截器
  2. 拦截器只能拦截控制器(controller),不能拦截jsp
  3. 拦截器可以中断用户请求
作用

将控制器(controller)中共同的方法放到拦截器中执行,减少控制器的代码。

基本示例

创建一个类MyInterceptor1,继承拦截器HandlerInterceptor,这个就是我们自定义的拦截器

@Component
public class MyInterceptor1 implements HandlerInterceptor {
    //这个方法是在访问控制器(controller)之前执行的
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("*********1、这个方法在控制器之前执行******************");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("*********3、这个方法在控制器之后执行******************");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("*********4、这个方法最后执行******************");
    }
}

创建一个InterceptorConfig,实现WebMvcConfigurer,并且把我们的MyInterceptor1注册到InterceptorConfig

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Autowired
    private MyInterceptor1 myInterceptor1;
    
    // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addInterceptor 注册拦截器
        //addPathPatterns 表示拦截的控制器
        //excludePathPatterns表示排除的控制器
        registry.addInterceptor(myInterceptor1).addPathPatterns("/test/*").excludePathPatterns("/test/test1");
    }
}

启动项目后,在浏览器输入http://localhost:8088/moyundong/test/test2的时候会调用拦截器信息,输入http://localhost:8088/moyundong/test/test1 的时候不会调用拦截器
::: warning 注意

  • MyInterceptor1拦截器里面做什么就要根据具体业务了,比如验证是否登录,是否有权限等等。
  • springboot2.x以后使用WebMvcConfigurer,在之前使用WebMvcConfigurerAdapter ,配置类要继承WebMvcConfigurerAdapter ,其它用法类似。
    :::

静态资源访问

我们在resources的目录下创建statics文件夹,里面放了一些静态文件,正常情况不能正常访问,添加如下代码就可以访问了。

// 这个方法是用来配置静态资源的,比如html,js,css,等等,解决静态资源访问问题。
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //addResourceHandler表示为前台访问的路径
        //addResourceLocations表示为files相对应的本地路径
        //我们在resources的目录下创建statics文件夹,里面放了一些静态文件,正常情况不能正常访问,添加如下代码就可以访问了。
        registry.addResourceHandler("/**").addResourceLocations("classpath:/statics/");
    }

创建好静态资源后,大家先不要加addResourceHandlers方法,直接在页面输入http://localhost:8088/moyundong/index.html或者
http://localhost:8088/moyundong/a.js的时候是不能访问静态资源的,加上上面的代码重启服务就可以访问了。

本节示例下载地址:java相关demo下载列表