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