1. 程式人生 > 程式設計 >SpringBoot中使用Cookie實現記住登入的示例程式碼

SpringBoot中使用Cookie實現記住登入的示例程式碼

最近在做專案,甲方提出每次登入都要輸入密碼,會很麻煩,要求實現一個記住登入狀態的功能,於是便使用 Cookie 實現該功能

一、Cookie 簡介

Cookie,一種儲存在使用者本地終端上的資料,有時也用其複數形式 Cookies。型別為“小型文字檔案”,是某些網站為了辨別使用者身份,進行 Session 跟蹤而儲存在使用者本地終端上的資料(通常經過加密),由使用者客戶端計算機暫時或永久儲存的資訊。

其實 Cookie 就是一個鍵和一個值構成的,隨著伺服器端的響應傳送給客戶端瀏覽器。然後客戶端瀏覽器會把 Cookie 儲存起來,當下一次再訪問伺服器時把 Cookie 再發送給伺服器。

1、Cookie 是 HTTP 協議的規範之一,它是伺服器和客戶端之間傳輸的小資料

2、首先由伺服器通過響應頭把 Cookie 傳輸給客戶端,客戶端會將 Cookie 儲存起來
3、當客戶端再次請求同一伺服器時,客戶端會在請求頭中新增該伺服器儲存的 Cookie,傳送給伺服器
4、Cookie 就是伺服器儲存在客戶端的資料
5、Cookie 就是一個鍵值對

SpringBoot中使用Cookie實現記住登入的示例程式碼

二、Cookie 使用

1、建立 Cookie

// Cookie 為鍵值對資料格式
Cookie cookie_username = new Cookie("cookie_username",username);

2、設定 Cookie 持久時間

// 即:過期時間,單位是:秒(s)
cookie_username.setMaxAge(30 * 24 * 60 * 60);

3、設定 Cookie 共享路徑

// 表示當前專案下都攜帶這個cookie
cookie_username.setPath(request.getContextPath());

4、向客戶端傳送 Cookie

// 使用 HttpServletResponse 物件向客戶端傳送 Cookie
response.addCookie(cookie_username);

5、銷燬 Cookie

// 根據 key 將 value 置空
Cookie cookie_username = new Cookie("cookie_username","");
// 設定持久時間為0
cookie_username.setMaxAge(0);
// 設定共享路徑
cookie_username.setPath(request.getContextPath());
// 向客戶端傳送 Cookie
response.addCookie(cookie_username);

三、進入正題

上面我們已經瞭解了 Cookie 是什麼,並且知道了 Cookie 的建立以及銷燬的方法,下面,我們就使用 Cookie 實現記住登入狀態的功能,整個專案基於 SpringBoot 實現

1、註冊攔截器

/**
* 註冊攔截器
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {

  @Autowired
  private LoginInterceptor loginHandlerInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    InterceptorRegistration ir = registry.addInterceptor(loginHandlerInterceptor);
    // 攔截路徑
    ir.addPathPatterns("/*");
    // 不攔截路徑
    List<String> irs = new ArrayList<String>();
    irs.add("/api/*");
    irs.add("/wechat/*");
    irs.add("/oauth");
    ir.excludePathPatterns(irs);
  }
}

我們攔截了所有的請求路徑,放開了 api、wechat 等請求路徑

這裡可能會有一個疑問,為什麼不放開請求登入介面的 api 請求路徑呢,原因是我們攔截登入請求,當我們請求登入介面時,我們已經登入過,那麼我們就無需進入登入介面,直接到主介面

我們使用了自定義的一個登入攔截:LoginInterceptor,在第二步我們會詳細講解其中的實現原理

2、登入攔截

/**
* 未登入攔截器
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {

  @Autowired
  private LoginDao dao;

  @Override
  public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception {
    // 獲得cookie
    Cookie[] cookies = request.getCookies();
    // 沒有cookie資訊,則重定向到登入介面
    if (null == cookies) {
      response.sendRedirect(request.getContextPath() + "/login");
      return false;
    }
    // 定義cookie_username,使用者的一些登入資訊,例如:使用者名稱,密碼等
    String cookie_username = null;
    // 獲取cookie裡面的一些使用者資訊
    for (Cookie item : cookies) {
      if ("cookie_username".equals(item.getName())) {
        cookie_username = item.getValue();
        break;
      }
    }
    // 如果cookie裡面沒有包含使用者的一些登入資訊,則重定向到登入介面
    if (StringUtils.isEmpty(cookie_username)) {
      response.sendRedirect(request.getContextPath() + "/login");
      return false;
    }
    // 獲取HttpSession物件
    HttpSession session = request.getSession();
    // 獲取我們登入後存在session中的使用者資訊,如果為空,表示session已經過期
    Object obj = session.getAttribute(Const.SYSTEM_USER_SESSION);
    if (null == obj) {
			// 根據使用者登入賬號獲取資料庫中的使用者資訊
    	UserInfo dbUser = dao.getUserInfoByAccount(cookie_username);
      // 將使用者儲存到session中
      session.setAttribute(Const.SYSTEM_USER_SESSION,dbUser);
    }
    // 已經登入
    return true;
  }
}

3、登入請求

控制層

/**
 * 執行登入
 */
 @PostMapping("login")
 @ResponseBody
 public String login(String username,String password,HttpSession session,HttpServletRequest request,HttpServletResponse response) {
   return service.doLogin(username.trim(),password.trim(),session,request,response).toJSONString();
 }

業務層

/**
 * 執行登入
 */
public JSONObject doLogin(String username,HttpServletResponse response) {
	// 最終返回的物件
  JSONObject res = new JSONObject();
  res.put("code",0);
  if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
    res.put("msg","請輸入手機號或密碼");
    return res;
  }
  UserInfo dbUser = dao.getUserInfoByAccount(username);
  if (null == dbUser) {
    res.put("msg","該賬號不存在,請檢查後重試");
    return res;
  }
  // 驗證密碼是否正確
  String newPassword = PasswordUtils.getMd5(password,username,dbUser.getSalt());
  if (!newPassword.equals(dbUser.getPassword())) {
    res.put("msg","手機號或密碼錯誤,請檢查後重試");
    return res;
  }
  // 判斷賬戶狀態
  if (1 != dbUser.getStatus()) {
    res.put("msg","該賬號已被凍結,請聯絡管理員");
    return res;
  }
  // 將登入使用者資訊儲存到session中
  session.setAttribute(Const.SYSTEM_USER_SESSION,dbUser);
  // 儲存cookie,實現自動登入
  Cookie cookie_username = new Cookie("cookie_username",username);
  // 設定cookie的持久化時間,30天
  cookie_username.setMaxAge(30 * 24 * 60 * 60);
  // 設定為當前專案下都攜帶這個cookie
  cookie_username.setPath(request.getContextPath());
  // 向客戶端傳送cookie
  response.addCookie(cookie_username);
  res.put("code",1);
  res.put("msg","登入成功");
  return res;
}

4、登出登入

/**
 * 退出登入
 */
@RequestMapping(value = "logout")
public String logout(HttpSession session,HttpServletResponse response) {
  // 刪除session裡面的使用者資訊
  session.removeAttribute(Const.SYSTEM_USER_SESSION);
  // 儲存cookie,實現自動登入
  Cookie cookie_username = new Cookie("cookie_username","");
  // 設定cookie的持久化時間,0
  cookie_username.setMaxAge(0);
  // 設定為當前專案下都攜帶這個cookie
  cookie_username.setPath(request.getContextPath());
  // 向客戶端傳送cookie
  response.addCookie(cookie_username);
  return "login";
}

登出登入時,我們需要刪除 session 裡面的使用者資訊,刪除 cookie 裡面的使用者資訊,然後請求到登入介面

四、總結

以上就是 SpringBoot 中使用 Cookie 實現記住登入功能,在專案中還算是比較實用的功能,希望能對正在閱讀的你一點點幫助和啟發,更多相關SpringBoot Cookie記住登入內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!