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("销毁");
    }
}
复制代码

 

posted on   大风吹过12138  阅读(22)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示