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

spring boot 配置过滤器filter, 拦截器interceptor, 监听器listener

程序员文章站 2022-05-01 11:50:01
...

spring boot 配置过滤器filter, 拦截器interceptor, 监听器listener


简单配置,如需深入学习和使用, 待续

项目地址码云

1. filter过滤器
过滤器是servlet提供, 用于对servlet的请求和详情进行过滤处理
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * spring boot 注解式过滤器,
 *  1. 定义一个类实现javax.servlet.annotation.WebFilter.Filter接口,并重写三大方法
 *          通常: init和destroy可以不用重写
 *          主要重写doFilter方法
 *  2. 使用注解@WebFilter(urlPatterns = "/*", filterName = "indexFilter")
 *          来定义这是一个拦截器, urlPatterns是拦截规则, filterName是拦截器名称
 *  3. 启动类上增加注解@ServletComponentScan, 启动即可,
 *
 * 拦截规则: urlPatterns = {"/*", "*.html", "/filter/test1/*"}
 *          分别对应: 所有请求, 以.html为后缀的所有请求, 指定路径的所有请求
 *
 * Created by noseew on 2018/1/5.
 */
/**
 * 注解方式配置filter需要@Component,@ServletComponentScan 或者将@ServletComponentScan加在启动类上
 */
//@Component
@ServletComponentScan
@WebFilter(urlPatterns = {"/*", "*.html", "/filter/test1/*"}, filterName = "indexFilter")
public class IndexFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("filter init...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter doFilter...");

        /**
         * 这里进行请求和相应的过滤处理
         */

        // filter chain filter过滤链
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("filter destroy...");
    }
}



2. interceptor拦截器
拦截器有spring框架提供, 和过滤器功能相似,拦截器能实现过滤器的基本功能, 此外能对请求响应页面等实现精确拦截控制, 个人觉得在前后端分离的项目中使用不多.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * spring boot 自定义拦截器
 *
 * Created by noseew on 2018/1/5.
 */

public class IndexInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(IndexInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        /**
         * 对来自后台的请求统一进行日志处理
         */
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        System.out.println(request.getParameterMap());
        logger.info(String.format("请求参数, url: %s, method: %s, uri: %s, params: %s", url, method, uri, queryString));
        System.out.println("在请求处理之前进行调用(Controller方法调用之前)");
        return true;// 只有返回true才会继续向下执行,返回false取消当前请求
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
    }
}

import org.song.servlet.config.interceptors.IndexInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * java配置方式, 配置interceptor 拦截器
 *
 * Created by noseew on 2018/1/5.
 */

@Configuration
public class IndexInterceptorConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(new IndexInterceptor()).addPathPatterns("/**").excludePathPatterns("/*");

        super.addInterceptors(registry);
    }
}



3. listener监听器
监听器listener, 个人使用不多, 主要对服务的事件进行监听,这里仅作参考
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * 自定义监听器配置
 *
 * 实现ServletContextListener并重写方法
 *
 * Created by noseew on 2018/1/6.
 */
/**
 * 可以配合 @[email protected] 放在自定义监听器上
 * 也可以方在启动类上
 * 但是不能同时使用多个
 * 也可以单独放@ServletComponentScan在启动类上, 可以配置多个监听器
 *
 */
//@Component
//@ServletComponentScan
@WebListener
public class ListenerServletContent implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("ListenerServletContent init...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("ListenerServletContent destroy...");
    }
}