Springboot 2.x 使用过滤器(Filter) ,拦截器(Intercepter),监听器(Listener)

spring 执行过程时 过滤器先执行,拦截器后执行

  1. 过滤器 Filter 的使用。
package cn.waimaolang.demo.middleware;

import cn.waimaolang.demo.utils.HttpResultUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @title 过滤器 根据 urlPatterns 的路径 进行过滤请求
 */
@WebFilter(urlPatterns = {"/home/*"},filterName = "IndexFilter")
public class IndexFilter implements Filter
{
    @Autowired
    HttpResultUtils httpResultUtils;
    /**
     * 框架启动的时候执行
     * 容器加载的时候调用
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init IndexMiddleware");
    }

    /**
     * 请求被拦截的时候进行调用
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setAttribute("name","wangjun");
        if(true){
            System.out.println("我是过滤器 xxx");
            // 允许继续执行 -> 走控制器
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            // 返回错误 ,禁止进入控制器
            response.setContentType("application/json;charset=utf-8");//指定返回的格式为JSON格式
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            String json = JSON.toJSONString(httpResultUtils.fail("过滤器阻止你进入xxx"));
            out.write(json);
            out.close();
        }
    }

    /**
     * 容器被销毁的时候被调用
     */
    @Override
    public void destroy() {
        System.out.println("destroy loginFilter");
    }
}

  1. 拦截器的使用
    (两步 1.自定义一个Interceptor 2. 注册)
// 定义一个拦截器
package cn.waimaolang.demo.middleware;

import cn.waimaolang.demo.utils.HttpResultUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 拦截器
 */
public class IndexIntercepter implements HandlerInterceptor
{

    @Autowired
    HttpResultUtils httpResultUtils;

    /**
     * 进入controller方法之前执行
     */
    @Override
    public boolean preHandle(
        HttpServletRequest request,
        HttpServletResponse response,
        Object handler
    ) throws Exception {

       // 权限验证
        String Secret = request.getHeader("Secret");
        if( StringUtils.isEmpty(Secret) || !Secret.equals("xxxxx")){
            // 权限验证失败
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(403);
            PrintWriter out = response.getWriter();// 这一句一定要在前面三句的后面,否则会导致设置ContentType无效
            out.write(JSONObject.toJSONString(new ApiResultResponse(403,"禁止访问,退出登陆")));
            out.close();
            return false;// 权限验证失败,不允许进入控制器
        }
        
        return true; // 进入控制器
    }

    /**
     * 调用完controller之后,视图渲染之前
     */
    @Override
    public void postHandle(
        HttpServletRequest request,
        HttpServletResponse response,
        Object handler,
        ModelAndView modelAndView
    ) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 一个请求完成之后,通常用于资源清理
     */
    @Override
    public void afterCompletion(
        HttpServletRequest request,
        HttpServletResponse response,
        Object handler,
        Exception ex
    ) throws Exception {
        System.out.println("执行完成 xxxx....");
        HandlerInterceptor.super.afterCompletion(request,response,handler,ex);
    }
}

//注册拦截器

package cn.waimaolang.demo.configura;

import cn.waimaolang.demo.middleware.IndexIntercepter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * web mvc 模式的 拦截器配置
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer
{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册多个Interceptor  注意路径的写法
        registry.addInterceptor(new IndexIntercepter()).addPathPatterns("/home/*");
        //registry.addInterceptor(new TwoIntercepter()).addPathPatterns("/api2/*/**");
        //注册某个拦截器的时候,同时排除某些不拦截的路径
        //registry.addInterceptor(new TwoIntercepter()).addPathPatterns("/api2/*/**").excludePathPatterns("/api2/xxx/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}

3.springboot 监听器教程
http://note.youdao.com/noteshare?id=c5df28a39ba57038089a20aad5011369&sub=ACDF29C77E04421298903C2BE6C7E822

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353