JSP cookie

Cookies are text files stored on the client. They hold a lot of track information. Based on servlet technology, JSP obviously provides support for HTTP cookies.

There are usually three steps to identifying repeat customers:

  • The server script sends a series of cookies to the browser. Such as name, age, ID number and so on.
  • The browser stores this information on the local machine in case it is needed.
  • The next time the browser sends any request to the server, it will also send these cookie information to the server, which then uses the information to identify the user or do something else.
  • This section will teach you how to set or reset cookies, how to access them and how to delete them.

    JSP cookie processing requires encoding and decoding of english, as follows:

    String   str   =   java.net.URLEncoder.encode("English", "UTF-8");            //coding
    String   str   =   java.net.URLDecoder.decode("codingAfter the string","UTF-8");   // decoding

    Anatomy of Cookies

    Cookies are usually set in HTTP headers (although JavaScript can set cookies directly in the browser). In JSP, setting a cookie requires sending the following headers to the server:

    HTTP/1.1 200 OK
    Date: Fri, 04 Feb 2015 21:03:38 GMT
    Server: Apache/1.3.9 (UNIX) PHP/4.0b3
    Set-Cookie: name=WELOOKUPS; expires=Friday, 04-Feb-17 22:03:38 GMT; 
                     path=/; domain=WELOOKUPS.com
    Connection: close
    Content-Type: text/html

    As you can see, the Set-Cookie header contains a key-value pair, a GMT (Greenwich Mean Time) time, a path, and a domain name. Key-value pairs are encoded as URLs. The expiration field is a directive that tells the browser when to clear this cookie.

    If the browser is configured to store cookies, it will save this information until it expires. If any page the user visits matches the path and domain name in the cookie, the browser will resend the cookie back to the server. The browser header looks like this:

    GET / HTTP/1.0
    Connection: Keep-Alive
    User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
    Host: zink.demon.co.uk:1126
    Accept: image/gif, */*
    Accept-Encoding: gzip
    Accept-Language: en
    Accept-Charset: iso-8859-1,*,utf-8
    Cookie: name=xyz

    JSP scripts access these cookies through the getCookies () method in the request object, which returns an array of Cookie objects.

    Servlet Cookie Method

    The following table lists the methods commonly used in cookie objects:

    Serial number Method & Description
    1 public void setDomain (String pattern)

    The domain name of the setting cookie, such as WELOOKUPS.com
    2 public String getDomain ()

    Get the domain name of the cookie, such as WELOOKUPS.com
    3 public void setMaxAge (int expiry)

    Setting cookie validity period, in seconds, the default validity period is the survival time of the current session
    4 public int getMaxAge ()

    Get the validity period of the cookie, in seconds. The default is -1, which means that the cookie will live until the browser is closed.
    5 public String getName ()

    Returns the name of the cookie. It cannot be modified after it is created.
    6 public void setValue (String newValue)

    Setting cookie value
    7 public String getValue ()

    Get the value of the cookie
    8 public void setPath (String uri)

    The path of the setting cookie, which defaults to all URLs in the current page directory, and all subdirectories in this directory
    9 public String getPath ()

    Get the path of the cookie
    10 public void setSecure (boolean flag)

    Indicate whether the cookie is to be transmitted encrypted
    11 public void setComment (String purpose)

    Setting annotations describe the purpose of cookies. Annotations will become very useful when the browser presents the cookie to the user
    12 public String getComment ()

    Returns a note describing the purpose of the cookie, or null if none

    Use JSP Setting cookie

    There are three steps to using a JSP Setting cookie:

    (1) Create a cookie object: Call the constructor of the cookie, using a cookie name and value as parameters, both of which are strings.

    Cookie cookie = new Cookie("key","value");

    Please keep in mind that neither the name nor the value can contain spaces or the following characters:

    [ ] ( ) = , " / ? @ : ;

    (2) Setting validity period: Calling the setMaxAge () function indicates how long (in seconds) the cookie is valid. The following operation sets the validity period to 24 hours.


    (3) Send the cookie to the HTTP response header: Call the response.addCookie () function to add a cookie to the HTTP response header.



    main.jsp The file code is shown below:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    <%@ page import="java.net.*" %>
       // coding,Solve english garbled characters   
       String str = URLEncoder.encode(request.getParameter("name"),"utf-8");  
       // Setting name withurl cookie 
       Cookie name = new Cookie("name",
       Cookie url = new Cookie("url",
       // Settingcookie expires in 24 hours。
       // Adding a cookie to the response header
       response.addCookie( name );
       response.addCookie( url );
    <title>Setting Cookie</title>
    <h1>Setting Cookie</h1>
    <li><p><b>Site name:</b>
       <%= request.getParameter("name")%>
       <%= request.getParameter("url")%>

    Here is a simple HTML form that submits client data into the main.jsp file via the GET method and sets the cookie:

    <!DOCTYPE html>
    <meta charset="utf-8">
    <title> Tutorial(WELOOKUPS.com)</title>
    <form action="main.jsp" method=GET>
    Site name: <input type="text" name="name">
    <br />
    URL: <input type="text" name="url" />
    <input type="submit" value="submit" />

    Save the above HTML code in the test.htm file.

    Place this file in the WebContent directory of the current jsp project (same directory as main.jsp).

    Submit the form data to the main.jsp file by visiting http: // localhost: 8080 / testjsp / test.html, the demo Gif diagram is as follows: