Simple use of Java cookies

/**
     * Set cookie
     * @param response
     * @param name cookie name
     * @param value cookie value
     * @param maxAge cookie life cycle in seconds
     */
    public void addCookie (HttpServletResponse response,String value){
        Cookie cookie = new Cookie("userid","213231");
        cookie.setMaxAge(1*24*60*60);// Set to 1day
        cookie.setPath("/");
        System.out.println("Added === ===========");
        response.addCookie(cookie);

    }


/**
     * Obtain userId according to Cookies to determine whether the user is logged in. If logged in, return the userid to obtain the User object, otherwise return the processing of the user not logged in.
     */
    public static String getUser (HttpServletRequest request) {
        String bbsUserId = "";
        // pass User ID obtained by page Cookies
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) { //traverse cookies
                Cookie c = cookies[ i];
                if (c.getName().equalsIgnoreCase("userid")) {
                    bbsUserId = c.getValue();
                }
            }
        }
        return bbsUserId;
    }

Then get the data object you want to store according to the returned bbsUserId, and get the data

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519855&siteId=291194637