Cookie free login case and cookie save session

main content:

If we log in to the account on csdn, after logging in, close the browser. When we open csdn again after a while, we will find that our account has been logged in. So how is this achieved? Let's implement it next.

Ideas and code analysis:

  1. First of all, we need to log in to the account first. After logging in, our user information is stored in the session. (The purpose of using session storage is to make sure you have logged in to your account when you write blogs or bookmark blogs later).
   HttpSession session = request.getSession();
   User user = userService.loginUser(username, password);
       session.setAttribute("user",user);
    
   
  1. We use cookies to store the user's session information, so that when the browser is closed and the session is accessed again, the current session is the same as the session before the closing, and the original session information can be obtained. (We know that the session is stored on the server and the cookie is stored on the browser. The session relies on the cookie. When we create a session, the browser will generate a cookie with the key name JSESSIONID to store this entire The session information of the second session, but when we close the browser, the value of JSESSIONID will be re-assigned, and the session information before closing the browser cannot be obtained).
//session.getId();此处的session就是对应上方的session
//获取登录账户的session  
//session是服务器储存,但是当浏览器关闭,服务器不关闭时重新打开浏览器。两次的session不是同一个。所以需要通过cookie保留原来的session数据
   			   Cookie userCookie = new Cookie("JSESSIONID",session.getId());
         	   userCookie.setMaxAge(60*60);//我这里设置的存活时间为一个小时
                 response.addCookie(userCookie);
  				   //获取用户名            
 				  Cookie usernameCookie= new Cookie("username",user.getUsername());
  				 //获取密码
                 Cookie passwordCookie = new Cookie("password",user.getPassword());

                 //设置cookie存活一小时
                 usernameCookie.setMaxAge(60*60);
                 passwordCookie.setMaxAge(60*60);
               
				//将cookie响应回去	
                 response.addCookie(usernameCookie);
                 response.addCookie(passwordCookie);
       
我们这时候已经登陆了(第一次登录)。
我们把账号和密码也存到cookie里面,用于之后每次打开浏览器后的用户判断,判断浏览器是否存在我们的信息,从而决定我们是否需要重新登录账号
                 
  1. At this point, when we close the browser and then open the browser, the value of the session obtained twice is the same, and we have stored the account information of the previous user in the cookie. Next, we can make a login judgment. (Take the code of my project as an example)
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        //存放cookie信息的map集合
        Map<String,String> cookieMap = new HashMap<>();
      
        //获取之前存放的cookies的信息
          Cookie[] cookies = request.getCookies();

          //获取cookie
            //1.先判断是否有cookie
          if (cookies!=null&&cookies.length!=0){
    
    
              System.out.println("有cookie信息,判断该用户");
              for (Cookie cookie:cookies){
    
    
              //2.往集合中存入用于用户名和密码判断的cookie值
                  if (cookie.getName().contains("username")||cookie.getName().contains("password")){
    
    
                      cookieMap.put(cookie.getName(),cookie.getValue());
                  }

              }
              //3.分别获取cookie存放的用户名和密码,用于验证(万一我要是修改了用户名密码,浏览器保存的是之前的,所以要先验证)
              String username = cookieMap.get("username");
              String password = cookieMap.get("password");
               //进行数据库访问
              User user =userService.loginUser(username, password);
               //判断是否存在
              if (user!=null){
    
    
                  //验证成功,直接登陆查看blog
                  System.out.println("用户信息已经存在,可以直接登陆了");
                 //既然数据库中有信息,说明验证成功,我就可以直接跳转到我的blog的页面了。
                  response.sendRedirect("/aishangboke/pageSearchServlet");
              }
              if (user==null){
    
    
                  //验证失败,重新登陆查看blog
                         //既然数据库中没有,说明验证失败,我就直接跳转到登陆页面重新登陆了。response.sendRedirect("/aishangboke/view/login.jsp");
              }
          } else{
    
    
          //如果cookie的长度为0,说明浏览器中没有存放cookie或者存放的cookie信息已经过期,跳转到重新登陆页面
              System.out.println("没有cookie信息,进行登陆");
              response.sendRedirect("/aishangboke/view/login.jsp");
          }
    }

summary

The code conversion of the core login case is the above.

When the server is running, you can write an interface to judge the cookie: 1. If the cookie does not exist, it means that you have not logged in. You can jump to the login page to log in to your account. 2. If the cookie exists, you can directly jump to my blog page (take csdnblog as an example) of the loginer information, and directly view the blog.

The subsequent code has nothing to do with the cookie. The cookie is equivalent to saying that it plays two functions here: 1. Stores the session information of the previous login. 2. Judge the account login.

problem:

We directly store the user's password of the loginer in the cookie, which is insecure. The user's account and password can be easily stolen, so we also need to encrypt the response. The encryption operation will be updated in the future.

Guess you like

Origin blog.csdn.net/zhang19903848257/article/details/107818861