SpringBoot+filter+listener+拦截器

Posted stt101517

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot+filter+listener+拦截器相关的知识,希望对你有一定的参考价值。

一、过滤器(filter)

  1.SpringBoot默认加载的过滤器

       characterEncodingFilter      

     hiddenHttpMethodFilter

     httpPutFormContentFilter

    requestContextFilter

  2.Filter的优先级

    Ordered.HIGHEST_PRECEDENCE

    Ordered.LOWEST_PRECEDENCE

    地位值意味着更高的优先级,自定义filter避免和默认的filter优先级一样,不然会冲突,注册filter的bean  filterRegistrationBean,同模块里面有默认filter   web---》servlet---》filter

  3.自定义filter

    使用servlet3.0注解进行配置

    启动类中加载@ServletComponenScan,进行扫描

    新建一个filter类,implements Filter,并实现对应的接口

    @WebFilter标记一个类为filter,被spring进行扫描         urlPatterns  匹配规则

package com.itcast.filter;

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


@WebFilter(urlPatterns = "/api/*",filterName = "loginFilter")
public class LoginFilter implements Filter {

    /**
     * 容器加載的時候調用
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init loginFilter");
    }

    /**
     * 请求被拦截的时候调用
     * @param request
     * @param response
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter loginFilter");
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        String username = request1.getParameter("username");
        if ("123".equals(username)){
            filterChain.doFilter(request,response);
        }else {
            response1.sendRedirect("index.html");
            return;
        }

    }

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

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class springBootAdminT {

    public static void main(String[] args) {
        SpringApplication.run(springBootAdminT.class,args);
    }
}

 二、servlet

package com.itcast.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name="userServlet" ,urlPatterns = "/v1/api/test/customs")
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("12345");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

 三、Listener

    常用的监听器:servletContextListener             httpSessionListtener              servletRequestListener

    

package com.itcast.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class RequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("===requestDestroyed===");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("=====requestInitialized======");
    }
}

四、Intecpter

package com.itcast.intecpter;

import org.springframework.boot.logging.LoggingInitializationContext;
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 CustomWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginIntercpter()).addPathPatterns("/api2/*/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
package com.itcast.intecpter;

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

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

public class LoginIntercpter implements HandlerInterceptor {

    /**
     *进入Controller之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginIntercpter---------->>>preHandle");
        return true;
    }

    /**
     * 调用完Controller之后,视图渲染之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginIntercpter---------->>>postHandle");
    }

    /**
     * 整个完成之后,通常用于资源清理
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginIntercpter---------->>>afterCompletion");
    }
}

 

       

 

 

 

以上是关于SpringBoot+filter+listener+拦截器的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot+filter+listener+拦截器

SpringBoot中使用Servlet,Filter,Listener

springBoot:web开发-Servlets, Filters, listeners

Springboot - -web应用开发-Servlets, Filters, listeners

(转)Springboot 中filter 注入对象

sprintboot 整合Servlet,Filter,Listener