Время жизни куки java

The Servlet API includes a Cookie class to wrap up the contents of a cookie plus a few attributes. There are generally two stages to using a cookie: first, at some point, we will want to ask the client set a cookie. Then, at some later stage, we’ll want to read the value of the cookie. Once we ask a client to set a cookie, then the client should send us back that cookie in any request to the domain/path that the cookie is defined for.

To ask the client to set a cookie, we create a Cookie object and then add it to the HTTP response that our Servlet sends back:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException < // read from the request the uesr's desired result per page Cookie ck = new Cookie("prefResultsPerPage", resPerPage); res.addCookie(ck); // now write response as normal. >

The constructor takes the essential parameters of a cookie: a name and value. There’s no absolute limit to the length of either, but the cookie specification 1 only recommends 4K as the minimum requirement for the length of a cookie, and it appears that some browsers have indeed imposed this rather meagre limit. According to the specification, the 4K limit includes name, value plus the attributes (in the format sent in the HTTP header). In other words, the answer to the question «what is the maximum length of a cookie?» is «fairly short, but it’s impossible to give a precise maximum that applies to all cases and/or all browsers».

As well as the necessary name and value, there are a few attributes that can be set on a cookie. Java doesn’t actually support all possible cookie attributes, but it does support the most common, useful ones as outlined below.

Maximum age (lifespan)

Probably the most commonly-set attribute is the maximum life span of the cookie. This is set via the setMaxAge() method, which takes an integer value in seconds. So to make a cookie expire after 30 minutes (a possible value for the timeout of a ‘session’), we could call:

Читайте также:  String list to number list python

As a piece of trivia, the cookie specification (but not Java’s Cookie API) actually allows decimal values for the maximum age, but it’s not clear why you’d need split-second granularity on the age of a cookie.

The default behaviour is that a cookie applies to:

  • requests to the same host from which the cookie was set;
  • requests to subpaths of the parent from which the cookie was set.

These mean that by default, a cookie set when returning www.domain.com/directory/page.html will apply to— i.e. be sent by the browser when requesting— any page inside www.domain.com/directory/, but would not apply to www.domain.com/index.html or to www.section.domain.com/anything.

To change these defaults, you can use two methods:

Cookie ck = new Cookie(. ); ck.setPath("/users/"); ck.setDomain(".mydomain.com");

In this case, we make the cookie applicable to any page or path inside /users/, and also make it apply to any subdomain of mydomain.com. Without the trailing dot, the domain is interpreted «literally». So a domain of www.mydomain.com wouldn’t apply to www.users.mydomain.com.

To tell the client to delete a cookie «now», add it to the response as above, but set its maximum age to zero. If you want the client to delete the cookie at the end of the current session, then set a negative maximum age (such as -1), though in fact this is the default behaviour.

«Secure» cookies

Cookies have a secure flag, indicating that the cookie should only be sent over a secure channel. The rationale is as follows: supposing that we set a session ID cookie in response to the user logging in over a secure connection. Since the session ID is what to the server «represents» the user name and password, we don’t want that session ID to ever be sent over an insecure connection and be vulnerable to eavesdropping. Setting the secure flag asks the client not to ever send that cookie over an insecure connection. In theory, «secure» and «insecure» are left to the interpretation of individual clients, but in practice «secure» means «HTTPS connection».

Читайте также:  Html table th font color css

Call setSecure(true) on a Cookie object in order to mark the corresponding cookie as secure.

Of course, setting setSecure() doesn’t magically turn insecure connections into secure connections. In order to set up a secure connection, you have to make sure that the client is making an HTTPS request and that your server is set up to deal with HTTPS.

Once we have set a cookie, then on subsequent requests to the Servlet, we will probably want to read the cookie value back.

1. See RFC 2965 for more information.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants. Follow @BitterCoffey

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.

Источник

Время жизни куки java

Куки представляют простейший способо хранения данных приложения. Куки хранятся в браузере польвователя в виде пары ключ-значение: с каждым уникальным ключом сопоставлется определенное значение. По ключу мы можем получить сохраненное в куках значение. Приложение на сервере может устанавливать куки и отправлять в ответе пользователю, после чего куки сохраняются в браузере. Когда клиент отправляет запроск приложению, то в запросе также отправляются и те куки, которые установленны данным приложением.

Куки могут быть двух типов. Одни куки хранятся только в течении сеанса. То есть когда пользователь закрывает вкладку браузера и прекращает работать с приложением, то куки сеанса уничтожаются. Второй тип куков — постоянные куки — хранятся в течение продолжительного времени (до 3 лет).

Следует учитывать некоторые ограничения. Прежде всего куки нередко ограничены по размеру (обычно не более 4 килобайт). Кроме того, обычно браузеры принимают не более 20 кук с одного сайта. Более того, в некоторых браузерах может быть отключена поддержка кук.

Для работы с куками сервлеты могут используют класс javax.servlet.http.Cookie . Для создания куки надо создать объект этого класса с помощью констуктора Cookie(String name, String value) , где name — ключ, а value — значение, которое сохраняется в куках. Стоит отметить, что мы можем сохранить в куках только строки.

Читайте также:  Php test if function is defined

Чтобы добавить куки в ответ клиенту у объекта 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 мы получим установлены куки:

Источник

Оцените статью