Filter实现权限拦截

登录页面
<html> <head> <title>Title</title> </head> <body> <h1 style="color: coral">登录</h1> <form action="${pageContext.request.contextPath}/servlet/login" method="post"> <input type="text" name="username"> <input type="submit"> </form> </body> </html>
从登录页面的表单获取用户输入的信息进行判断,决定重定向去登陆成功页面还是错误页面
public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); if (username.equals("admin")){ req.getSession().setAttribute("USER_SESSION",req.getSession().getId()); resp.sendRedirect(req.getContextPath()+"/sys/success.jsp"); }else { resp.sendRedirect(req.getContextPath()+"/error.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
登录成功页
<html> <head> <title>登录成功</title> </head> <body> <h1 style="color: chartreuse">登录成功</h1> <h2>主页</h2> <p><a href="${pageContext.request.contextPath}/servlet/logout">注销</a> </p> </body> </html><html> <head> <title>登录成功</title> </head> <body> <h1 style="color: chartreuse">登录成功</h1> <h2>主页</h2> <p><a href="${pageContext.request.contextPath}/servlet/logout">注销</a> </p> </body> </html>
错误页
<html> <head> <title>Title</title> </head> <body> <h1>错误</h1> <a href="${pageContext.request.contextPath}/login.jsp" >返回登录页面</a> </body> </html>
过滤器:进行用户的session判断,当用户session为空时都会跳到错误页
public class SysFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("初始化"); } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest)req; HttpServletResponse response=(HttpServletResponse) resp; if (request.getSession().getAttribute("USER_SESSION")==null){ response.sendRedirect(request.getContextPath()+"/error.jsp"); } chain.doFilter(req,resp); } @Override public void destroy() { System.out.println("销毁"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!