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 2023-01-17 02:21  大风吹过12138  阅读(27)  评论(0)    收藏  举报

导航