前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot拦截器的简单使用

SpringBoot拦截器的简单使用

作者头像
止术
发布2020-09-15 10:12:57
4460
发布2020-09-15 10:12:57
举报
文章被收录于专栏:求道

SpringBoot拦截器的简单使用

Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Spring提供的HandlerInterceptor(拦截器)。他和Filter(过滤器)类似,但是可以提供比过滤器更加精准的控制!拦截器可以在请求执行请求资源的 前 中 后 三个时间段进行处理!

一、代码实现

SpringBoot所提供的的拦截器相对来说较为简单,只需要实现HandlerInterceptor这个接口就可以了

代码语言:javascript
复制
package com.demo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author huangfu
 */
public class TestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求执行前先拦截");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("这个方法中你可以对ModelAndView进行操作,请求资源执行后,DispatcherServlet进行视图的渲染之前");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求执行后拦截,DispatcherServlet进行视图的渲染之后,多用关闭资源");
    }
}

然后将这个拦截器注册到配置类

代码语言:javascript
复制
package com.demo.conf;

import com.demo.interceptor.TestInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TestInterceptor())
                //这个会拦截所求的路径
                .addPathPatterns("/**");
        //.excludePathPatterns("/login")  排除某些路径
    }
}

运行结果:

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-10-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 JAVA程序狗 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SpringBoot拦截器的简单使用
    • 一、代码实现
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档