ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

springboot 配置和使用过滤器

2020-09-16 17:01:00  阅读:11  来源: 互联网

标签:HttpServletRequest springboot 配置 HttpServletResponse 过滤器 import servlet javax St


首先在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);

    }
}

标签:HttpServletRequest,springboot,配置,HttpServletResponse,过滤器,import,servlet,javax,St
来源: https://www.cnblogs.com/semiprimenumber/p/13680059.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有