码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot+filter+listener+拦截器

时间:2020-06-03 23:08:50      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:servlet   rgs   color   handler   registry   nbsp   super   mvcc   config   

一、过滤器(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+拦截器

标签:servlet   rgs   color   handler   registry   nbsp   super   mvcc   config   

原文地址:https://www.cnblogs.com/stt101517/p/13033958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!