Servlet Cookie processing
Cookie is a text file stored on the client computer and retains a variety oftracking information. Java Servlet clearly supports HTTP Cookie.
Identifying the returned user consists of three steps:
The server script sends a set of Cookie to the browser. For example: name, age or identification number, etc.
Browsers store this information on the local computer for future use.
The next time the browser sends any request to the Web server, the browser sends this Cookie information to the server, which the server uses to identify the user.
This chapter shows you how to set or reset Cookie, how to access them, and how to delete them.
Servlet Cookie processing requires encoding and decoding of Chinese as follows:
String str = java.net.URLEncoder.encode("Chinese","UTF-8"); //code
String str = java.net.URLDecoder.decode("Encoded string","UTF-8"); // code
Cookie analysis
Cookie is usually set in the HTTP header information (although JavaScript can also set a Cookie directly on the browser). Setting the Servlet of Cookie sends the following header information:
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=runoob.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name-value pair, a GMT date, a path, and a field. The name and value are encoded by URL. expires
a field is an instruction that tells the browser to “forget” the Cookie after a given time and date.
If the browser is configured to store Cookie, it will retain this information until the expiration date. If the user’s browser points to any page that matches the path and domain of the Cookie, it resends the Cookie to the server. The header information for the browser may be as follows:
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
Servlet can then use the request method request.getCookies()
access Cookie, which returns an array of Cookie objects.
Servlet Cookie method
Serial number |
Method & description |
---|---|
1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
The following is a list of useful methods that can be used to manipulate Cookie in Servlet.
Set up Cookie through Servlet
Setting up Cookie through Servlet involves three steps:
(1)create a Cookie
object: you can call the Cookie constructor with the cookie name and cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Remember that neither the name nor the value should contain spaces or any ofthe following characters:
[ ] ( ) = , " / ? @ : ;
(2)set the maximum life cycle: you can use the setMaxAge
method to specify cookie
the time (in seconds) that can be kept valid. The following will set a maximum validity period of 24 hours cookie
.
cookie.setMaxAge(60*60*24);
(3)send Cookie to HTTP response header: you can use the response.addCookie
to add the Cookie in the HTTP response header, as follows:
response.addCookie(cookie);
Example
Let’s modify our form data instance to set the Cookie for the first and lastname.
package com.runoob.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
@WebServlet("/HelloForm")
public class HelloForm extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloForm() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// Create cookies for first and last names
Cookie name = new Cookie("name",
URLEncoder.encode(request.getParameter("name"), "UTF-8")); // Chinese transcoding
Cookie url = new Cookie("url",
request.getParameter("url"));
// Set the expiration date for two cookies to 24 hours later
name.setMaxAge(60*60*24);
url.setMaxAge(60*60*24);
// Add two cookies to the response header
response.addCookie( name );
response.addCookie( url );
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "Set Cookie Instance";
String docType = "<!DOCTYPE html>\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>site name:</b>:"
+ request.getParameter("name") + "\n</li>" +
" <li><b>site URL:</b>:"
+ request.getParameter("url") + "\n</li>" +
"</ul>\n" +
"</body></html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Compile the Servlet above HelloForm
and in the web.xml
create the appropriate entry in the file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<!-- Class name -->
<servlet-name>HelloForm</servlet-name>
<!-- The package it is in -->
<servlet-class>com.runoob.test.HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<!-- Visited website -->
<url-pattern>/TomcatTest/HelloForm</url-pattern>
</servlet-mapping>
</web-app>
Finally, try the following HTML page to call Servlet.