当使用了Spring Boot框架,需要对filter进行改造
最简单的方式,就是在类前添加以下两个注解:
@SpringBootApplication //标明这是一个启动类
@ServletComponentScan //让springboot扫描此类
实例,登录拦截:
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter({"/admin/*","/teacher/*","/student/*"})
@SpringBootApplication //标明这是一个启动类
@ServletComponentScan //让springboot扫描此类
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
//禁止未登录的用户
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String uri = request.getRequestURI();
boolean login_flag = false;
if (uri.startsWith("/admin/") && request.getSession().getAttribute("admin")==null){
login_flag = true;
}else if(uri.startsWith("/teacher/") && request.getSession().getAttribute("teacher")==null){
login_flag = true;
}else if(uri.startsWith("/student/") && request.getSession().getAttribute("student")==null){
login_flag = true;
}
if(login_flag==true){ // 触发了任意一个规则
response.setCharacterEncoding("utf-8");
String s = "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>未登录</title>";
s+="<script>function countDown(){var time=document.getElementById('Time');";
s+="if(time.innerHTML==0){window.location.href='"+request.getContextPath()+"/login.html'}";
s+="else{time.innerHTML=time.innerHTML-1}}window.setInterval('countDown()',1000);</script>";
s+="<style>p{font-size:50px;text-align:center}#Time{font-size:100px;text-align:center}</style></head>";
s+="<body><p>用户,您还未登录!</p><p>即将在3秒后自动跳转登录界面,点击<a href='"+request.getContextPath()+"/login.html'>";
s+="立刻跳转</a></p><p id='Time'>3</p></body></html>";
response.getWriter().println(s);
}else{ // 放行
filterChain.doFilter(request,response);
}
}
@Override
public void destroy() {
}
}
本篇完,还有疑问?留下评论吧