Filter Filter implements login and logout Demo

13. Common applications of filters

Filter small demo:

insert image description here

the whole idea:

  • front end:

    • A form gets the username and passes it to the Servlet (the url of the registered servlet is located through the action of the form)
    • A success interface that provides a logout button (directly jump to the index interface after logout)
    • An error interface that provides a return to login button (click to jump to the index interface)
  • Servlet:

    • LoginServlet: Get the username to judge, and then redirect the index
    • LogoutServlet: implement removeAttribute(), then redirect index
  • Filter:

    Forcibly convert ServletRequest into HTTPServletRequest, obtain Session to judge whether it is empty, and redirect index

It took nearly 2 hours to completely rewrite it after understanding it by myself, woo woo woo!

Think again:

  1. Create a login.jsp page, and the front end gets the username and sends it to /servlet/login

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <h1>登录</h1>
    <form action="/servlet/login" method="post">
        <input type="text" name="username">
        <input type="submit">
    </form>
    </body>
    </html>
    
  2. Create a LoginServlet, process the obtained username, and judge and forward the success.jsp or error page!

    public class LoginServlet extends HttpServlet {
          
          
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
          
            String username = req.getParameter("username");
            //判断登录,并重定向到对应jsp页面
            if (username.equals("tom")){
          
          
                //这里是我整个Demo的一个大问题,深刻理解了Session中保存键值对,
                //创建了一个Constant类静态定义一个键USER_SESSION,用来存放Session的ID
                req.getSession().setAttribute(Constant.USER_SESSION,req.getSession().getId());
                resp.sendRedirect("/sys/success.jsp");
            }else {
          
          
                resp.sendRedirect("/error.jsp");
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
          
            doGet(req, resp);
        }
    }
    
  3. After the page jump is realized, it is divided into two parts

    • success part
      • show success
      • A logout hyperlink, passed to /servlet/logout, and then create a LogoutServlet to log out of the Session
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <h1>Success!</h1>
    <p><a href="/servlet/logout">注销</a></p>
    </body>
    </html>
    
    public class LogoutServlet extends HttpServlet {
          
          
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
          
            //通过静态的键获取存的值(Session的ID)
            if (req.getSession().getAttribute(Constant.USER_SESSION)!=null){
          
          
                req.getSession().removeAttribute(Constant.USER_SESSION);
                resp.sendRedirect("/login.jsp");
            }else{
          
          
                resp.sendRedirect("/login.jsp");
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
          
            doGet(req, resp);
        }
    }
    
    • error part

      • It is simply to log in again: hyperlink to login.jsp
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>Title</title>
      </head>
      <body>
      <h1>Error!</h1>
      <p><a href="login.jsp">返回重新登录</a></p>
      </body>
      </html>
      

    Note: the a tag can use the form of "/sevlet/logout" to request to the registered Servlet, and realize the jump through the Servlet, or directly "login.jsp" to jump directly to the jsp page

  4. add filter

    At this point, the operation of login, logout and re-login has been realized, but there is still a BUG, ​​that is, I can still access it directly by typing success.jsp in the address bar, but I have obviously clicked logout, and theoretically it should be called to logout Session The method, (I printed the ID after remove, if it shows NULL, then the session must have been logged out), but I can access it, I hope the boss can help me analyze the reason.

    But this is not the point. Aim at the general direction and add a filter to the success interface to filter and automatically jump to the error interface after accessing the success interface without a session.

    public void init(FilterConfig filterConfig) throws ServletException {
          
          
        
    }
    
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
          
          
        HttpServletRequest req =  (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        if (req.getSession().getAttribute(Constant.USER_SESSION)==null){
          
          
            resp.sendRedirect("/error.jsp");
        }
        //自己测试的时候,这句话没有加,确实容易犯错
        filterChain.doFilter(servletRequest, servletResponse);
    }
    
    public void destroy() {
          
          
    
    }
    

This is the end of the whole demo. To be honest, the whole demo is very simple step by step when watching Kuangshen make it, but it is really difficult to write it from 0 by yourself. Through this method, you can first read it as a whole and then realize it yourself. It is true that I have gained a lot, but it is a bit time-consuming, except that the BUG cannot be directly screened out by itself, or the foundation is not solid enough, keep going!

Guess you like

Origin blog.csdn.net/Xiao_tongtong/article/details/124065686