- How to use Cookies in Java web application
- 1. How to create a cookie
- 2. How to read cookies
- 3. How to update a cookie
- 4. How to delete a cookie
- 5. Java Cookies Example Project
- Java Cookies Example
- Add Cookies
- Read Cookies
- Delete Cookies
- API References:
- Other Java Servlet Tutorials:
- About the Author:
- Servlet and cookies in java
- Servlet and cookies in java
- Constructor of Cookie class
- Useful Methods of Cookie class
- Other methods required for using Cookies
- How to create Cookie?
- How to delete Cookie?
- How to get Cookies?
- Simple example of Servlet Cookies
- index.html
- FirstServlet.java
- SecondServlet.java
- web.xml
- Output
- Feedback
- Help Others, Please Share
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
How to use Cookies in Java web application
In this tutorial, you will learn how to create, update, read and delete cookies in a Java web application.
A cookie is a small amount of data which is stored in the web browser and transferred between requests and responses through HTTP headers. A cookie has a name and value, plus option attributes like comment, path, domain, max age,… Cookies are commonly used to implement simple, temporary data storage on the client side, such as session management, remember password, shopping cart items, etc.
In Java Servlet API, the javax.servlet.http. Cookie class represents a cookie.
1. How to create a cookie
String name = "Cookie name"; String value = "Cookie value"; Cookie cookie = new Cookie(name, value);
This will send appropriate HTTP headers to the client, and the browser stores the cookie on user’s computer.
Besides the mandatory attributes name and value, you can also specify additional information for a cookie using the following methods:
setComment (String) : specifies a comment that describes the cookie’s purpose. For example:
cookie.setComment("This cookie stores username of the customer");
setDomain (String) : specifies the domain name within which this cookie is visible. By default, cookies are only returned to the server that sent them. So setting the domain name makes the cookies available for different servers under the same domain name. For example:
cookie.setDomain(".codejava.net");
This cookie will be available for all servers under the domain codejava.net. Note that the domain name should starts by a dot. The following example sets domain of the cookie to localhost:
setHttpOnly (boolean) : if set to true, Javascript can’t read this cookie on the client side, which can prevent some kinds of cross-site scripting attacks. For example:
setMaxAge (int) : specifies how long the cookie is stored in user’s computer, in seconds. If not set, the cookie is deleted when the web browser exits. For example:
cookie.setMaxAge(7 * 24 * 60 * 60);
This sets the cookie’s life is 7 days (= 24 hours x 60 minutes x 60 seconds) and it is still stored on the user’s computer when the browser exists.
setPath (String) : use this method if you want to restrict the cookie to be available for a certain path (and its subpaths) on the server. For example:
setSecure (boolean) : if set to true, the cookie is sent from the browser to the server only when using secure protocol (HTTPS or SSL). Default is false.
2. How to read cookies
To read cookies sent from the browser to the server, call getCookies() method on a HttpServletRequest object in a Java servlet class. This method returns an array of Cookie objects that are visible to the current request. For example, the following code read all cookies and print its names and values:
Cookie[] cookies = request.getCookies(); PrintWriter writer = response.getWriter(); for (Cookie aCookie : cookies) < String name = aCookie.getName(); String value = aCookie.getValue(); writer.println(name + " brush:java">String username = null; for (Cookie aCookie : cookies) < String name = aCookie.getName(); if (name.equals("username")) < username = aCookie.getValue(); break; >>
3. How to update a cookie
To update an existing cookie, you need to create a new cookie with the same name and add it to the response. For example:
String name = "Cookie name"; String value = "New value"; Cookie cookie = new Cookie(name, value); response.addCookie(cookie);
4. How to delete a cookie
To remove a cookie from the browser’s cache, you need to create a new cookie with the same name, set its max age to zero and add it to the response. For example:
Cookie cookie = new Cookie("username", ""); cookie.setMaxAge(0); response.addCookie(cookie);
5. Java Cookies Example Project
The following sample project helps you learn how to use cookies in a Java web application. Create a simple Java web project. Code the home page ( index.jsp ) as follows:
Java Cookies Example
Add Cookies
Read Cookies
Delete Cookies
Create the AddCookiesServlet class to handle the hyperlink ‘Add Cookies’ with the following code:
package net.codejava; import java.io.IOException; 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; @WebServlet("/add_cookies") public class AddCookiesServlet extends HttpServlet < private static final long serialVersionUID = 1L; private static int cookieCount; public AddCookiesServlet() < >protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < String name = "Cookie" + (++cookieCount); String value = String.valueOf(System.currentTimeMillis()); Cookie cookie = new Cookie(name, value); response.addCookie(cookie); response.getWriter().println("A cookie has been created successfully!"); >>
Create the ReadCookiesServlet class to read all cookies visible to the application, with the following code:
package net.codejava; import java.io.IOException; import java.io.PrintWriter; 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; @WebServlet("/read_cookies") public class ReadCookiesServlet extends HttpServlet < private static final long serialVersionUID = 1L; public ReadCookiesServlet() < >protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < PrintWriter writer = response.getWriter(); Cookie[] cookies = request.getCookies(); if (cookies == null) < writer.println("No cookies found"); >else < writer.println("Number of cookies: " + cookies.length); for (Cookie aCookie : cookies) < String name = aCookie.getName(); String value = aCookie.getValue(); writer.println(name + " lazy" style="display: block; margin-left: auto; margin-right: auto;" src="https://www.codejava.net/images/articles/javaee/servlet/cookie/Java_test_read_cookies.png" alt="Java test read cookies" width="600" height="211" />As you can see, the first cookie with name JSESSIONID is created by the server to manage user’s session.And to test removal of cookies, create the DeleteCookiesServlet class with the following code:package net.codejava; import java.io.IOException; import java.io.PrintWriter; 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; @WebServlet("/delete_cookies") public class DeleteCookiesServlet extends HttpServlet < private static final long serialVersionUID = 1L; public DeleteCookiesServlet() < >protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < PrintWriter writer = response.getWriter(); Cookie[] cookies = request.getCookies(); if (cookies != null) < for (Cookie aCookie : cookies) < aCookie.setMaxAge(0); response.addCookie(aCookie); >writer.println("All cookies have been deleted!"); > else < writer.println("No cookies found"); >> >API References:
Other Java Servlet Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Servlet and cookies in java
Куки представляют простейший способо хранения данных приложения. Куки хранятся в браузере польвователя в виде пары ключ-значение: с каждым уникальным ключом сопоставлется определенное значение. По ключу мы можем получить сохраненное в куках значение. Приложение на сервере может устанавливать куки и отправлять в ответе пользователю, после чего куки сохраняются в браузере. Когда клиент отправляет запроск приложению, то в запросе также отправляются и те куки, которые установленны данным приложением.
Куки могут быть двух типов. Одни куки хранятся только в течении сеанса. То есть когда пользователь закрывает вкладку браузера и прекращает работать с приложением, то куки сеанса уничтожаются. Второй тип куков - постоянные куки - хранятся в течение продолжительного времени (до 3 лет).
Следует учитывать некоторые ограничения. Прежде всего куки нередко ограничены по размеру (обычно не более 4 килобайт). Кроме того, обычно браузеры принимают не более 20 кук с одного сайта. Более того, в некоторых браузерах может быть отключена поддержка кук.
Для работы с куками сервлеты могут используют класс javax.servlet.http.Cookie . Для создания куки надо создать объект этого класса с помощью констуктора Cookie(String name, String value) , где name - ключ, а value - значение, которое сохраняется в куках. Стоит отметить, что мы можем сохранить в куках только строки.
Чтобы добавить куки в ответ клиенту у объекта HttpServletResponse применяется метод addCookie(Cookie c)
При создании куки мы можем использовать ряд методов объекта Cookie для установки и получения отдельных параметров:
- setMaxAge(int maxAgeInSeconds) : устанавливает время в секундах, в течение которого будут существовать куки. Специальное значение -1 указывает, что куки будут существовать только в течение сессии и после закрытия браузера будут удалены.
- setValue(String value) : устанавливает хранимое значение.
- getMaxAge() : возвращает время хранения кук.
- getName() : возвращает ключ кук.
- getValue() : возвращает значение кук.
Например, установка куки с названием "user" и значением "Tom":
Cookie cookie = new Cookie("user", "Tom"); response.addCookie(cookie);
Чтобы получить куки, которые приходят в запросе от клиента, применяется метод getCookies() класса HttpServletRequest.
Например, получение куки по имени:
Cookie[] cookies = request.getCookies(); String cookieName = "user"; Cookie cookie = null; if(cookies !=null) < for(Cookie c: cookies) < if(cookieName.equals(c.getName())) < cookie = c; break; >> >
Получение куки по имени немного громоздко, поскольку нам надо перебрать набор полученных кук и сравнить из им с нужным ключом. Поэтому при частном использовании, как правило, определять вспомогаельные методы, которые инкапсулируют подобную функционалность.
Например, определим сервлет SetServlet, который будет устанавливать куки:
import java.io.IOException; import java.io.PrintWriter; 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; @WebServlet("/set") public class SetServlet extends HttpServlet < protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < PrintWriter out = response.getWriter(); try < response.addCookie(new Cookie("user", "Tom")); out.println("Cookie is set"); >finally < out.close(); >> >
В данном случае устанавливается куки user, которая хранит строку "Tom".
Определим сервдет HelloServlet, который получает эту куку:
import java.io.IOException; import java.io.PrintWriter; 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; @WebServlet("/hello") public class HelloServlet extends HttpServlet < protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < Cookie[] cookies = request.getCookies(); String cookieName = "user"; Cookie cookie = null; if(cookies !=null) < for(Cookie c: cookies) < if(cookieName.equals(c.getName())) < cookie = c; break; >> > PrintWriter out = response.getWriter(); try < out.println("Name: " + cookie.getValue()); >finally < out.close(); >> >
Таким образом, при обращении к сервлету SetServlet произойдет установка кук, а при обращении к сервлету HelloServlet мы получим установлены куки:
Servlet and cookies in java
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.
Constructor of Cookie class
Constructor | Description |
---|---|
Cookie() | constructs a cookie. |
Cookie(String name, String value) | constructs a cookie with a specified name and value. |
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
Method | Description |
---|---|
public void setMaxAge(int expiry) | Sets the maximum age of the cookie in seconds. |
public String getName() | Returns the name of the cookie. The name cannot be changed after creation. |
public String getValue() | Returns the value of the cookie. |
public void setName(String name) | changes the name of the cookie. |
public void setValue(String value) | changes the value of the cookie. |
Other methods required for using Cookies
- public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.
- public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.
How to create Cookie?
Let's see the simple code to create cookie.
How to delete Cookie?
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
How to get Cookies?
Let's see the simple code to get all the cookies.
Simple example of Servlet Cookies
In this example, we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well that session corresponds to the particular user. So if you access it from too many browsers with different values, you will get the different value.
index.html
FirstServlet.java
SecondServlet.java
web.xml
Output
For Videos Join Our Youtube Channel: Join Now
Feedback
Help Others, Please Share
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter