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);
    
        }
    }
    
    
  • 相关阅读:
    C的xml编程文章链接
    《Android内核剖析》读书笔记 第13章 View工作原理【View树遍历】
    在MyEclipse中编写Web Project,编码设置全集合
    “克强经济学”绝非是通缩经济学
    VS2008--无法找到“XXX.exe”的调试信息,或者调试信息不匹配
    Dubbo架构设计详解--转载
    Beyond MySQL --Branching the popular database--转载
    eclipse中不能找到dubbo.xsd解决方法
    Java + MongoDB Hello World Example--转载
    Dubbo入门实例--转载
  • 原文地址:https://www.cnblogs.com/semiprimenumber/p/13680059.html
Copyright © 2011-2022 走看看