Java Cookie Session Technology

1. Introduction to Cookies

A cookie is a file stored on a computer. When we use our computer to browse the web, the server generates a certificate and returns it to our computer. This certificate is a cookie. Generally speaking, a cookie is a file written by the server to the client, and it can also be called a browser cache.

Simply put, it can read and save some behavioral information generated when you visit a website, which is usually encrypted, otherwise it will violate the user's privacy. Cookies can also help speed up second visits. Usually, when we visit some web pages, the system will prompt us whether to save the user name and password. The next time we log in, we can automatically log in without having to log in again.

2. Create and send cookies

1. Create a cookie and send it to the client as a response header

Cookie cookie = new Cookie(String cookieName, String cookieValue);

2. Send Cookie to the client

response.addCooike(Cookie cookie);

3. Some common APIs of cookies

1. Set the persistence time of the cookie on the client

cookie.setMaxAge(int seconds)

Note: If the persistence time is not set, the cookie will be stored in the browser's memory, and the browser will close the cookie information destruction (session-level cookie). If the persistence time is set, the cookie information will be persisted to the browser's disk file inside

2. Set the carrying path of the cookie

cookie.setPath(String path)

Note: If you do not set the carrying path, the cookie information will carry the cookie information on the path where the web resource that generated the cookie is accessed

3. Send Cookie to the client

response.addCooike(Cookie cookie)

4. Delete the client's cookie

cookie.setMaxAge(0)

Note: If you want to delete the stored cookie information on the client, just use the cookie with the same name and the same path as the persistence time of 0 to overwrite it

5. The server obtains the Cookie carried by the client and sends it to the server-side as a request header.

// Get all cookies through request
Cookie[] cookies = request.getCookies();

// Traverse the Cookie array, get the Cookie we want by the name of the Cookie
for (Cookie cookie : cookies) {     if (cookie.getName.equals("cookieName")){         String cookieValue = cookie.getValue();     } }



4. Example of Java Servlet Cookie

1. Generate cookies

@WebServlet(name = "CookieServlet",urlPatterns = "/cookie")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie=new Cookie("goods","cup");//不能使用中文
        cookie.setMaxAge(60*10);
        cookie.setPath("/hello/getCookie");

        Cookie cookie1=new Cookie("userName","xiaoming");

        response.addCookie(cookie);
        response.addCookie(cookie1);

    }
}

 2. Display cookies

@WebServlet(name = "GetCookieServlet",urlPatterns = "/getCookie")
public class GetCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (name.equals("userName")){
                String cookieValue = cookie.getValue();
                response.getWriter().write("userName:"+cookieValue);
            }
        }
    }
}

5. The last visit time of the case record website

@WebServlet(name = "TimeServlet", urlPatterns = "/time")
public class TimeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //记录访问时间并其通过cookie加入到响应头
        Date date = new Date();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-hh:mm:ss");
        String time = simpleDateFormat.format(date);

        Cookie cookie = new Cookie("time", time);
        cookie.setMaxAge(60*60*24);
        response.addCookie(cookie);
        response.setContentType("text/html;charset=utf-8");
        //获取客户端浏览器发送过来的cookie数据
        Cookie[] cookies = request.getCookies();
        String timeValue = null;
        for (Cookie cookie1 : cookies) {

            if (cookie1.getName().equals("time")) {
                timeValue = cookie1.getValue();
            }
        }
        if (timeValue == null) {
            response.getWriter().write("欢迎您访问我们的网站");
        } else {
            response.getWriter().write("您上次访问网站的时间是:" + timeValue);
        }


    }
}

Guess you like

Origin blog.csdn.net/mshxuyi/article/details/131287708