过滤器

主要用于登录和拦截
package com.book.filter;

import com.book.entity.User;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.*;

import java.io.IOException;

@WebFilter("/*")
public class MainFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
String url =req.getRequestURI().toString();
if(!url.contains("/static/") && !url.endsWith("login")&& !url.endsWith("index")) {
HttpSession session = req.getSession();
User user=(User)session.getAttribute("user");
if(user==null)
{
res.sendRedirect("login");
return;
}
}
chain.doFilter(req, res);

}

}
默认登录页面是http://localhost:8080/book_manager/login
当访问其他网址时将返回登录页面

posted @ 2024-11-04 22:48  雨花阁  阅读(2)  评论(0编辑  收藏  举报