10 browser-side storage techniques Introduction (to achieve 'Remember Me')

Transfer: https://www.funtl.com/zh/spring-web/%E6%B5%8F%E8%A7%88%E5%99%A8%E7%AB%AF%E5%AD%98%E5 % 82% A8% E6% 8A % 80% E6% 9C% AF% E7% AE% 80% E4% BB% 8B.html #% E9% 99% 84% EF% BC% 9Acookieutils

Browser-side storage techniques Introduction

Cookie refers to data stored on the user's local terminal, and it is associated with a particular Web page or site. Cookie data is automatically sent between the Web browser and the Web server transmission, that is to say when the HTTP request is sent, will be stored at the request of all the Cookie domain name value to the Web server, the server-side script can read and write memory operating in the client's Cookie's.

LocalStorage

In HTML5, the new joined a localStorage feature, this feature is mainly used to be used as a local storage, to solve the problem of shortage of storage space Cookie (Cookie Cookie in each storage space for 4k), localStorage general browser support is 5M size, this localStorage will be different in different browsers.

SessionStorage

The only point of difference SessionStorage LocalStorage is LocalStorage is a permanent storage, and SessionStorage belong when the session ended, SessionStorage key-value pairs will be cleared.

UserData、GlobalStorage、Google Gear

With these three have some limitations, such as

  • userData IE browser is unique, its capacity can reach 640K, this embodiment reliable, no need to install plugins, but it is only effective in IE
  • globalStorage applies to Firefox 2+ browsers, like IE's userData
  • google gear is Google development to a local storage techniques, the need to install Gear assembly

Flash ShareObject(Flash Cookie)

In this way can solve two disadvantages Cookie stored mentioned above, but also cross-browser, it should be said is the best local storage solutions. However, the need to insert a Flash in the page when the browser is not installed Flash controls can not be used. Fortunately, very few users do not have Flash installed.

Annex: CookieUtils

package com.funtl.leeshop.commons.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Cookie 工具类
 * <p>Title: CookieUtils</p>
 * <p>Description: </p>
 *
 * @author Lusifer
 * @version 1.0.0
 * @date 2017/12/10 22:00
 */
public final class CookieUtils {

    /**
     * 得到Cookie的值, 不编码
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        return getCookieValue(request, cookieName, false);
    }

    /**
     * 得到Cookie的值,
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    if (isDecoder) {
                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                    } else {
                        retValue = cookieList[i].getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    /**
     * 得到Cookie的值,
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue) {
        setCookie(request, response, cookieName, cookieValue, -1);
    }

    /**
     * 设置Cookie的值 在指定时间内生效,但不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue, int cookieMaxage) {
        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
    }

    /**
     * 设置Cookie的值 不设置生效时间,但编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue, boolean isEncode) {
        setCookie(request, response, cookieName, cookieValue, -1, isEncode);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue, int cookieMaxage, boolean isEncode) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue, int cookieMaxage, String encodeString) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
    }

    /**
     * 删除Cookie带cookie域名
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
                                    String cookieName) {
        doSetCookie(request, response, cookieName, "", -1, false);
    }

    /**
     * 设置Cookie的值,并使其在指定时间内生效
     *
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
                                          String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request) {// 设置域名的cookie
                String domainName = getDomainName(request);
//                System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置Cookie的值,并使其在指定时间内生效
     *
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
                                          String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else {
                cookieValue = URLEncoder.encode(cookieValue, encodeString);
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request) {// 设置域名的cookie
                String domainName = getDomainName(request);
//                System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到cookie的域名
     */
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;

        String serverName = request.getRequestURL().toString();
        if (serverName == null || serverName.equals("")) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            serverName = serverName.substring(7);
            final int end = serverName.indexOf("/");
            serverName = serverName.substring(0, end);
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                domainName = "." + domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }

        if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        return domainName;
    }

}

 The realization of 'Remember Me'

  • Cookie is first necessary tools copied in
  • Then when you log in is successful, judgment is not checked 'Remember me', and if so, the user name and password stored in the Cookie; otherwise, delete the corresponding record in the Cookie.
  • When entering the login page, to get a Cookie, then where to write in it? Can be downloaded doGet () in which there is a problem, not initially into the / login in, how to do it? Can jump from page to / login, obtain user information in the Cookie doGet (), a request transmitted by login.jsp

login.jsp

<form action="/login" method="post">
         
                <input type="email" name="email" class="form-control" placeholder="邮箱" value="${email}">
             
                <input type="password" name="password" class="form-control" placeholder="密码" value="${password}">
              
                <input type="checkbox" name="isRemember" ${isRemember!=null?"checked":""}> 记住我
                       
                 <button type="submit" class="btn btn-primary btn-block btn-flat">登录</button>
</form>

LoginController

@WebServlet(name = "LoginController", urlPatterns = "/login")
public class LoginController extends HttpServlet {

    private static final String COOKIE_USER_INFO="userInfo";

    protected void doGet(HttpServletRequest req, HttpServletResponse resq) throws ServletException, IOException {
        String userInfo=CookieUtils.getCookieValue(req,COOKIE_USER_INFO);
        if(!StringUtils.isBlank(userInfo))
        {
            String[] userInfoArray=userInfo.split(":");
            String email=userInfoArray[0];
            String password =userInfoArray[1];
            req.setAttribute("email",email);
            req.setAttribute("password",password);
            req.setAttribute("isRemember",true);
        }
        req.getRequestDispatcher("/login.jsp").forward(req,resq);

    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resq) throws ServletException, IOException{

      //  ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
       /* SpringContext context=new SpringContext();
        UserService userService=(UserService) context.getBean("userService");*/
        //UserService userService=new UserServiceImpl();
        UserService userService=SpringContext.getBean("userService");
        String email=req.getParameter("email");
        String password = req.getParameter("password");
        User user=userService.login(email,password);

        //记住我
        Boolean isRemember=req.getParameter("isRemember")==null?false:true;

        //登录失败的处理
        if(user==null){
            req.setAttribute("message","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resq);
        }

        //登录成功的处理
        else{
            //如果用户点击记住我
            if(isRemember==true)
            {
                CookieUtils.setCookie(req,resq,COOKIE_USER_INFO,String.format("%s:%s",email,password));
            }
            else {
                CookieUtils.deleteCookie(req,resq,COOKIE_USER_INFO);
            }
            resq.sendRedirect("/main.jsp");
        }

    }

}

meta automatically jump

  <meta http-equiv="Refresh" content="0; url=/login"/>

 

Guess you like

Origin blog.csdn.net/shmily_syw/article/details/91854642