Blog system back-end design (6) - Realize the mandatory login function required by the login page

Implementation page requires mandatory login


When the user visits the list page/details page/edit page, the user is required to be logged in.
If the user has not logged in, it will be forced to jump to the login page.

Implementation ideas


When the page is loaded, a new ajax is specially initiated. (Multiple ajax requests can be sent in one page)
If you take the list page as an example, first send a request to get the list page, and then send an ajax to get the user's login status when getting the list page.
If the user is already logged in, it will not happen What is; if you are not logged in, you will be redirected to the login page.

1. Agree on front-end and back-end interaction interfaces


The agreed request here is GET, and the path is /login.

The response is HTTP/1.1 200 OK. The information returned is the current logged-in user. If not logged in, a user object with userId as 0 will be returned.

User information is described in the picture below.

2. Implement the backend code

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
     resp.setContentType("application/json; charset=utf8");
     // 如果用户未登录,这里的会话就拿不到
     HttpSession session = req.getSession(false);
     if (session == null) {
    
    
         // 未登录,返回一个空的 user 对象
         User user = new User();
         String respJson = objectMapper.writeValueAsString(user);
         resp.getWriter().write(respJson);
         return;
     }
     User user = (User) session.getAttribute("user");
     // 登录成功,确保拿到的回话不是空,再判定一次
     if (user == null) {
    
    
         user = new User();
         String respJson = objectMapper.writeValueAsString(user);
         resp.getWriter().write(respJson);
         return;
     }
     // 确定了拿出了会话,也就是用户的信息,就直接返回即可
     String respJaon = objectMapper.writeValueAsString(user);
     resp.getWriter().write(respJaon);
 }

3. Modify the front-end code


Modify the code of the blog list page, and add the following code to the list page, edit page, and details page.

 function checkLogin() {
    
    
      $.ajax({
    
    
          type: 'get',
          url: 'login',
          success: function(body) {
    
    
              if (body.userId && body.userId > 0) {
    
    
                  // 登录成功!
                  console.log("当前用户已经登录!!!");
              } else {
    
    
                  // 当前未登录,跳转到登录页面
                  location.assign('blog.in.html');
              }
          }
      });
  }
        
  checkLogin();


The statement location.assign('blog.in.html') fills in the path of the login page.

If you have not logged in at this time, you will automatically jump to the login page when you log in to the details page, list page, and edit page.

Guess you like

Origin blog.csdn.net/m0_63033419/article/details/130742535