溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Cookie使用過(guò)濾器如何實(shí)現(xiàn)客戶訪問(wèn)登錄功能

發(fā)布時(shí)間:2020-10-16 15:37:15 來(lái)源:億速云 閱讀:233 作者:小新 欄目:編程語(yǔ)言

這篇文章主要介紹了Cookie使用過(guò)濾器如何實(shí)現(xiàn)客戶訪問(wèn)登錄功能,具有一定借鑒價(jià)值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

1.cookies

何為Cookies:Cookies為 Web 應(yīng)用程序保存用戶相關(guān)信息提供了一種有用的方法。例如,當(dāng)用戶訪問(wèn)您的站點(diǎn)時(shí),您可以利用 Cookie 保存用戶首選項(xiàng)或其他信息,這樣,當(dāng)用戶下次再訪問(wèn)您的站點(diǎn)時(shí),應(yīng)用程序就可以檢索以前保存的信息。

我們看一下是如何保存cookies和如何刪除cookies

保存cookies

String newUserName = null;
try {
  newUserName = URLEncoder.encode(username, "UTF-8");//把用戶名轉(zhuǎn)碼,防止用戶名是中文,cookies保存中文取出會(huì)亂碼
} catch (UnsupportedEncodingException e) {
  e.printStackTrace();
}
Cookie nameCookie = new Cookie("username", newUserName);
String pwdMd5Cook = MD5Util.MD5(Pwd);
Cookie pwdCookie = new Cookie("pwd", pwdMd5Cook);// 保存加密后的密碼
nameCookie.setMaxAge(60 * 60 * 24 * 365);// 用戶名保存一年
pwdCookie.setMaxAge(60 * 60 * 24 * 30);// 密碼保存30天
// 發(fā)送Cookie信息到瀏覽器
response.addCookie(nameCookie);
response.addCookie(pwdCookie);

刪除cookies,刪除很簡(jiǎn)單,但值得注意的時(shí),刪除cookies,跟保存cookies一定要在同一個(gè)控制層,不然會(huì)找不到保存的cookies,導(dǎo)致刪除不了

Cookie cookie = new Cookie("pwd", null);
cookie.setMaxAge(0);// 刪除密碼cookie
response.addCookie(cookie);

2.Filter-過(guò)濾器

Filter也稱之為過(guò)濾器,它是Servlet技術(shù)中最實(shí)用的技術(shù),Web開(kāi)發(fā)人員通過(guò)Filter技術(shù),對(duì)web服務(wù)器管理的所有web資源:例如Jsp, Servlet, 靜態(tài)圖片文件或靜態(tài) html 文件等進(jìn)行攔截,從而實(shí)現(xiàn)一些特殊的功能。例如實(shí)現(xiàn)URL級(jí)別的權(quán)限訪問(wèn)控制、過(guò)濾敏感詞匯、壓縮響應(yīng)信息等一些高級(jí)功能。

實(shí)現(xiàn)方法:繼承Filter接口,并實(shí)現(xiàn)其doFilter方法。在web.xml文件中對(duì)編寫的filter類進(jìn)行注冊(cè),并設(shè)置它所能攔截的資源

<filter>指定一個(gè)過(guò)濾器。
<filter-name>用于為過(guò)濾器指定一個(gè)名字,該元素的內(nèi)容不能為空。
<filter-class>元素用于指定過(guò)濾器的完整的限定類名。
<init-param>元素用于為過(guò)濾器指定初始化參數(shù),它的子元素<param-name>指定參數(shù)的名字,<param-value>指定參數(shù)的值。
在過(guò)濾器中,可以使用FilterConfig接口對(duì)象來(lái)訪問(wèn)初始化參數(shù)。
<filter-mapping>元素用于設(shè)置一個(gè) Filter 所負(fù)責(zé)攔截的資源。一個(gè)Filter攔截的資源可通過(guò)兩種方式來(lái)指定:Servlet 名稱和資源訪問(wèn)的請(qǐng)求路徑
<filter-name>子元素用于設(shè)置filter的注冊(cè)名稱。該值必須是在<filter>元素中聲明過(guò)的過(guò)濾器的名字
<url-pattern>設(shè)置 filter 所攔截的請(qǐng)求路徑(過(guò)濾器關(guān)聯(lián)的URL樣式)
<servlet-name>指定過(guò)濾器所攔截的Servlet名稱。
<filter>
  <filter-name>suicaiFilter</filter-name>
  <filter-class>com.suicai.filter.suicaiFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>suicaiFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

下面看一下實(shí)際應(yīng)用代碼:

public class suicaiFilter implements Filter {
  @Override
  public void destroy() {
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req=(HttpServletRequest)request;
    HttpServletResponse res=(HttpServletResponse)response;
    HttpSession session = req.getSession();
    String requestURI = req.getRequestURI();
    String param = req.getQueryString();
    String url = req.getServletPath();
    if(param!=null){
      url = url+"?"+param;
    }
    if(requestURI.contains("js") || requestURI.contains("css") || requestURI.contains("images")){
      //不過(guò)濾css,js,images等靜態(tài)資源
      chain.doFilter(request, response);
    }else if(requestURI.contains("/info/")||requestURI.contains("/gys/")){
      //過(guò)濾前臺(tái)訪問(wèn)頁(yè)面,跟前臺(tái)個(gè)人中心(供應(yīng)商后臺(tái)),自動(dòng)登錄一次,登錄不成功不進(jìn)行操作,個(gè)人中心登錄不成功,則跳到登錄頁(yè)面
      ProviderInfo providerInfo = (ProviderInfo) session.getAttribute("providerInfo_gys");
      String IsAutomaticLogin = (String) session.getAttribute("IsAutomaticLogin");//是否已經(jīng)走過(guò)自動(dòng)登錄流程標(biāo)識(shí)
      if(requestURI.contains("/info/") && !requestURI.contains("/login")){
        //訪問(wèn)門戶等不需要必須登錄的(登錄除外),只嘗試登錄一次,如果不成功,不進(jìn)行操作
        if(providerInfo==null && IsAutomaticLogin == null){
          req.getSession().setAttribute("goURL", url);
          res.sendRedirect(req.getContextPath() + "/common/automaticLogin");
        }else if(providerInfo==null && IsAutomaticLogin != null ){
          chain.doFilter(request, response);
        }else{
          chain.doFilter(request, response);
        }
      }else if(requestURI.contains("/gys/")){//訪問(wèn)個(gè)人中心,自登陸一次,不成功跳轉(zhuǎn)到登錄頁(yè)面
        if(providerInfo==null && IsAutomaticLogin == null){
          req.getSession().setAttribute("goURL", url);
          res.sendRedirect(req.getContextPath() + "/common/automaticLogin");
        }else if(providerInfo==null && IsAutomaticLogin != null ){
          session.setAttribute("redirectUrl", url);
          res.sendRedirect(req.getContextPath() + "/login.jsp?redirectUrl="+url);
        }else{
          chain.doFilter(request, response);
        }
      }else{
        chain.doFilter(request, response);
      }
    }else{
      //不過(guò)濾
      chain.doFilter(request, response);
    }
  }
  @Override
  public void init(FilterConfig arg0) throws ServletException {
  }
}

從代碼中可知,需要一個(gè)是否已經(jīng)自動(dòng)登錄過(guò)的標(biāo)識(shí)(IsAutomaticLogin),該標(biāo)識(shí)是在走自動(dòng)登錄時(shí)(不管成不成功)保存起來(lái)的

3.結(jié)合上面提供知識(shí),下面為整體代碼展示,如發(fā)現(xiàn)不對(duì)地方,歡迎大家指出

@Controller
@RequestMapping("/common")
public class CommonController{
  /**
   * 自動(dòng)登錄方法
   * @param request
   * @param response
   * @param username
   * @param pwd
   * @param ProviderInfo 供應(yīng)商賬戶信息model
   * @return
   */
  @RequestMapping("/automaticLogin")
  public String automaticLogin(HttpServletRequest request,ServletResponse response,@CookieValue(value = "username", required = false) String username,@CookieValue(value = "pwd", required = false) String pwd,ProviderInfo ProviderInfo) {
    // 保存需求登錄前的鏈接
    String goURL = (String) session.getAttribute("goURL");
    if (username == null) {//cookies中沒(méi)有用戶名,肯定不需要自動(dòng)登錄
      session.setAttribute("IsAutomaticLogin", "0");
      return "redirect:" + goURL;
    } else {
      try {
        username = URLDecoder.decode(username, "UTF-8");//轉(zhuǎn)義,防止中文
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    // cookie失效 session一定為空,因?yàn)榈卿洉r(shí),一定會(huì)把用戶名保存在cookie中
    if ("".equals(username) || username == null) {// 使用session登錄不了,不進(jìn)行任何操作,不在進(jìn)入這個(gè)方法
      session.setAttribute("IsAutomaticLogin", "0");
      return "redirect:" + goURL;
    } else {
      // cookie中沒(méi)有密碼,判斷session為不為空,如果為空,說(shuō)明沒(méi)有登錄,如果不為空,說(shuō)明,用戶是選擇不記住密碼登錄(所以cookie中沒(méi)有密碼)
      if ("".equals(pwd) || pwd == null) {
        ProviderInfo customer1 = (ProviderInfo) session.getAttribute("providerInfo_gys");
        if (customer1 == null) {// 使用session登錄不了,不進(jìn)行任何操作,不在進(jìn)入這個(gè)方法
          session.setAttribute("IsAutomaticLogin", "0");
          return "redirect:" + goURL;
        } else {
          // 已經(jīng)登錄,不再進(jìn)入這個(gè)方法
          return "redirect:" + goURL;
        }
      } else {
        // cookie中有密碼,判斷session為不為空,如果為空,說(shuō)明沒(méi)有登錄,如果不為空,說(shuō)明已經(jīng)登錄
        ProviderInfo customer1 = (ProviderInfo) session.getAttribute("providerInfo_gys");
        if (customer1 == null) {// 當(dāng)前沒(méi)有登錄,調(diào)用cookies中的用戶名跟密碼進(jìn)行登錄
          // 進(jìn)行自動(dòng)登錄操作,登錄成功后返回原來(lái)頁(yè)面
          ProviderInfo customer3 = ValidateDate(username);
          customer3.setPwd(pwd);
          customer3.setAccountType(6);
          ProviderInfo customer2 = infoService.login(customer3);//調(diào)用登錄方法
          if (customer2 == null) {// 自動(dòng)登錄失敗,不再進(jìn)入這個(gè)方法
            session.setAttribute("IsAutomaticLogin", "0");
            return "redirect:" + goURL;
          } else {
            // 登陸成功保存客戶信息到session
            session.setAttribute("providerInfo_gys",customer2);
            return "redirect:" + goURL;
          }
        } else {
          return "redirect:" + goURL;
        }
      }
    }
  }
  /**
   * 用戶登陸
   * @param request
   * @param response
   * @param cus
   * @return
   */
  @RequestMapping("/UserLogin")
  @ResponseBody
  public Map<String, Object> goLogin(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("ProviderInfo") ProviderInfo cus) {
    /*省略一些邏輯判斷*/
    cus.setPwd(MD5Util.MD5(Pwd));
    ProviderInfo providerInfo = infoService.login(cus);
    Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
    if (providerInfo == null) {
      // 登陸失敗,重新跳轉(zhuǎn)到登陸頁(yè)面
      map.put("error", "密碼錯(cuò)誤");
      return map;
    }else{
      String newUserName = null;
      if (remember_me.equals("1")) {// 有選擇一個(gè)月免登錄
        try {
          newUserName = URLEncoder.encode(username, "UTF-8");
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        Cookie nameCookie = new Cookie("username", newUserName);
        String pwdMd5Cook = MD5Util.MD5(Pwd);
        Cookie pwdCookie = new Cookie("pwd", pwdMd5Cook);// 保存加密后的密碼+"create"
        nameCookie.setMaxAge(60 * 60 * 24 * 365);// 用戶名保存一年
        pwdCookie.setMaxAge(60 * 60 * 24 * 30);// 密碼保存30天
        // 發(fā)送Cookie信息到瀏覽器
        response.addCookie(nameCookie);
        response.addCookie(pwdCookie);
        session.setAttribute("IsAutomaticLogin",null);
      }else{//沒(méi)有選擇,刪除上次可能已經(jīng)選擇自動(dòng)登錄時(shí)的密碼
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
          for (Cookie cookie : cookies) {
            cookieMap.put(cookie.getName(), cookie);
          }
        }
        if (cookies != null) {
          for (int i = 0; i < cookies.length; i++) {
            if (cookieMap.containsKey("pwd")) {
              Cookie cookie = new Cookie("pwd", null);
              cookie.setMaxAge(0);// 刪除密碼cookie
              response.addCookie(cookie);
            }
          }
        }
      }
      // 登陸成功,保存當(dāng)前user信息,保存客戶信息到session
      map.put("ProviderInfo", providerInfo);
      map.put("goURL", session.getAttribute("goURL"));
      session.setAttribute("providerInfo_gys", providerInfo);
      return map;
    }else {
      map.put("error", "該供應(yīng)商賬號(hào)不存在");
      return map;
    }
  }
  /**
   * 注銷
   * @return
   */
  @RequestMapping("/logout")
  public String logout(HttpServletResponse response) {
    Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
    Cookie[] cookies = request.getCookies();
    if (null != cookies) {
      for (Cookie cookie : cookies) {
        cookieMap.put(cookie.getName(), cookie);
      }
    }
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookieMap.containsKey("pwd")) {
          Cookie cookie = new Cookie("pwd", null);
          cookie.setMaxAge(0);// 刪除密碼cookie
          response.addCookie(cookie);
        }
      }
    }
    session.setAttribute("providerInfo_gys", null);
    return "/index";
  }
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享Cookie使用過(guò)濾器如何實(shí)現(xiàn)客戶訪問(wèn)登錄功能內(nèi)容對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問(wèn)題就找億速云,詳細(xì)的解決方法等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI