Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JSP cookies are processed


May 12, 2021 JSP


Table of contents


JSP cookies are processed

Cookies are text files stored on the client that hold a large amount of track information. Based on servlet technology, JSP is clearly able to provide support for HTTP cookies.

There are usually three steps to identify 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 of need.
  • The next time the browser sends any request to the server, it sends the cookie information to the server at the same time, which the server then uses to identify the user or do something else.

This section will teach you how to set up or reset cookies, how to access them, and how to delete them.


Cookie anatomy

Cookies are usually set in the HTTP header (although JavaScript can set cookies directly in the browser). I n JSP, setting up a cookie requires sending the following information header to the server:

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

As you can see, the Set-Cookie header contains a key-value pair, a GMT (GMT), a path, a domain name. K ey value pairs are encoded as URLs. The expiration domain is an instruction that tells the browser when to clear the cookie.

If the browser is configured to store cookies, it will save this information until it expires. I f any of the pages visited by the user match the path and domain name in the cookie, the browser will send the cookie back to the server. T he information header on the browser side 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 cookies method

The following table lists commonly used methods in cookie objects:

Serial number Method . . .
1 public void setDomain(String pattern)

Set the domain name of the cookie, such as w3cschool.cn

2 public String getDomain()

Get the domain name of the cookie, such as w3cschool.cn

3 public void setMaxAge(int expiry)

Set the cookie expiration date, in seconds, with the default expiration date for the current session's survival time

4 public int getMaxAge()

Get the cookie expiration date, in seconds, which defaults to -1, indicating that the cookie will live until the browser closes

5 public String getName()

Returns the name of the cookie, which cannot be modified after it has been created

6 public void setValue(String newValue)

Set the value of the cookie

7 public String getValue()

Get the value of the cookie

8 public void setPath(String uri)

Set the path to the cookie, which defaults to all URLs in the current page directory, as well as all subdirectts in this directory

9 public String getPath()

Get the path to the cookie

10 public void setSecure(boolean flag)

Indicates whether the cookie is to be transmitted encrypted

11 public void setComment(String purpose)

Set comments to describe the purpose of the cookie. Comments become useful when the browser presents cookies to the user

12 public String getComment()

Returns a comment describing the purpose of the cookie and, if not, null


Use JSP to set cookies

Setting cookies with JSP consists of three steps:

(1) Create a cookie object: Call the cookie constructor and use a cookie name and value as arguments, they are all strings.

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

It is important to keep in mind that neither the name nor the value can contain spaces or characters such as:

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

(2) Set the expiration date: Calling the setMaxAge() function indicates how long the cookie is valid in seconds. The following action will be valid for 24 hours.

cookie.setMaxAge(60*60*24); 

(3) Send cookies to the HTTP response header: Call the response.addcookie() function to add cookies to the HTTP response header.

response.addCookie(cookie);

Example demonstration

<%    
// 为 first_namelast_name设置cookie
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",request.getParameter("last_name"));
// 设置cookie过期时间为24小时。
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// 在响应头部添加cookie
response.addCookie( firstName );
response.addCookie( lastName );
%> <html> <head> <title>Setting Cookies</title> </head> <body>
<center> <h1>Setting Cookies</h1> </center> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>

Put the above file in the installation directory of the .lt;Tomcat/webapps/ROOT directory, and then access http://localhost:8080/hello.jsp the following output:

JSP cookies are processed

Try entering First Name and Last Name, and then click the Submit button, which will display first name and last name on your screen, and set the first name and last name cookies, which will be sent to the server the next time you click the Submit button.


Use JSP to read cookies

To read cookies, you need to call the request.getcookies() method to get an array of javax.servlet.http.cookie objects, and then traverse the array, using the getName() method and getValue() method to get the name and value of each cookie.

< />< h3="" />

Let's read the cookies in the last example.

<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%    
Cookie cookie = null;
Cookie[] cookies = null;
// 获取cookies的数据,是一个数组
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];

out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println("<h2>No cookies founds</h2>"); } %> </body> </html>

If you set the first name cookie to "John" and the last name to "Player" and access http://localhost:8080/main.jsp, you will get the following output:

Found Cookies Name and Value
Name : first_name, Value: John 
Name : last_name, Value: Player

Use JSP to remove cookies

Removing cookies is easy. If you want to delete a cookie, follow the steps given below:

  • Get an existing cookie and store it in a cookie object.
  • Set the validity of the cookie to 0.
  • Add this cookie back into the response header.

Example demonstration

The following program removes a cookie first_name", and the next time you run .jsp main, first_name will be null.

<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
  <h1>Reading Cookies</h1>
</center>
<%    
Cookie cookie = null;
Cookie[] cookies = null;
// 获取当前域名下的cookies,是一个数组
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ){
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } %> </body> </html>

By accessing it, you'll get the following output:

Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player

If you visit http://localhost:8080/main.jsp again, you will get the following results:

Found Cookies Name and Value
Name : last_name, Value: Player

You can also manually remove cookies from your browser. Click on the Tools menu item, then select Internet Options, and click on the Delete cookies to delete all cookies.

< />