zoukankan      html  css  js  c++  java
  • springboot 配置和使用过滤器

    首先在Application文件中添加注解@ServletComponentScan自动扫描当前类的同包以及子包,这样才能将filter装入bean
    package com.example.academy;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    
    @ServletComponentScan
    @SpringBootApplication
    @MapperScan("com.example.academy.dao")
    public class AcademyApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(AcademyApplication.class, args);
        }
    
    }
    
    
    然后配置自己的filter
    package com.example.academy.filter;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    
    @WebFilter(urlPatterns = "/*")
    public class LoginFilter implements Filter {
        private final String[] notFilterUrl = {"/index", "/login", "js", "css", "images", "fonts"};//不拦截列表
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            //判断是否为HttpServletRequest/HttpServletResponse请求
            if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
                throw new ServletException("拦截器仅支持HTTP请求");
            }
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String uri = request.getRequestURI();
            boolean notFilter = false;
            //遍历不拦截列表并查找是否存在指定值
            for (String str : notFilterUrl) {
                if (uri.contains(str)) {
                    notFilter = true;
                    break;
                }
            }
            System.out.println("过滤器工作");
            HttpSession session = request.getSession();
            Object user = session.getAttribute("id");
            if (user == null && !notFilter) {
                response.sendRedirect("index");
                return;
            }
            filterChain.doFilter(request, response);
    
        }
    }
    
    
  • 相关阅读:
    一、
    【2019-11-25】美好需要主动去发现
    《软件方法(上)》读书笔记
    【2019-11-24】读书让人美丽
    【2019-11-23】让别人来管理自己
    【2019-11-22】不聪明只有靠笨方法了
    【2019-11-21】要像人一样思考
    【2019-11-20】作为丈夫的反省
    【2019-11-19】基础科学的意义发现
    【2019-11-18】重新审视一下自己的思维
  • 原文地址:https://www.cnblogs.com/semiprimenumber/p/13680059.html
Copyright © 2011-2022 走看看