Что такое куки?
- Cookies — это текстовые файлы, которые хранятся на клиентском компьютере.
- Они используются для отслеживания информации для различных целей.
- Он поддерживает HTTP куки с использованием технологии сервлетов
- Файлы cookie устанавливаются в заголовке HTTP.
- Если браузер настроен для хранения файлов cookie, он будет хранить информацию до истечения срока годности.
Ниже приведены методы cookie:
-
Публичный void setDomain (строковый домен)
Используется для установки домена, к которому применяется cookie
-
Открытая строка getDomain ()
Используется для получения домена, к которому применяется cookie
-
Public void setMaxAge (int expiry)
Устанавливает максимальное время, которое должно применяться до истечения срока действия куки
-
Публичный intgetMaxAge ()
Возвращает максимальный возраст куки
-
Открытая строка getName ()
Возвращает имя куки
-
Public void setValue (строковое значение)
Устанавливает значение, связанное с cookie
-
Публичная строка getValue ()
Получить значение, связанное с cookie
-
Public void setPath (String path)
Устанавливает путь, к которому применяется cookie
-
Публичная строка getPath ()
Получает путь, к которому применяется cookie
-
Открытый void setSecure (логический флаг)
Он должен быть отправлен через зашифрованные соединения или нет.
-
Public void setComment (String cmt)
Это описывает цель куки
-
Public String getComment()
It the returns the cookie comments which has been described.
How to Handle Cookies in JSP
- Creating the cookie object
- Setting the maximum age
- Sending the cookie in HTTP response headers
Example:
In this example, we are creating cookies of username and email and add age to the cookie for 10 hours and trying to get the variable names in the action_cookie.jsp
Action_cookie.jsp.
- <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>Guru Cookie</title>
- </head>
- <body>
- <form action="action_cookie_main.jsp" method="GET">
- Username: <input type="text" name="username">
- <br />
- Email: <input type="text" name="email" />
- <input type="submit" value="Submit" />
- </form>
- </body>
- </html>
Action_cookie_main.jsp
- <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <%
- Cookie username = new Cookie("username",
- request.getParameter("username"));
- Cookie email = new Cookie("email",
- request.getParameter("email"));
- username.setMaxAge(60*60*10);
- email.setMaxAge(60*60*10);
- // Add both the cookies in the response header.
- response.addCookie( username );
- response.addCookie( email );
- %>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>Guru Cookie JSP</title>
- </head>
- <body>
- <b>Username:</b>
- <%= request.getParameter("username")%>
- <b>Email:</b>
- <%= request.getParameter("email")%>
- </body>
- </html>
Explanation of the code:
Action_cookie.jsp
Code Line 10-15: Here we are taking a form which has to be processed in action_cookie_main.jsp. Also, we are taking two fields «username» and «email» which has to be taken input from the user with a submit button.
Action_cookie_main.jsp
Code Line 6-9: Creating two cookie objects of «username» and «email» using request.getParameter.
Code Line 12-13: Here we are adding age to both the cookies, which have been created of 10 hours i.e. cookies will expire in that age.
Code Line 16-17: Adding cookies to the session of username and email and these two cookies can fetched when requested by getParameter().
Output:
When you execute the above code you get the following output:
Когда мы выполняем action_cookie.jsp, мы получаем два поля username и email, для этого требуется ввод данных пользователем, а затем мы нажимаем кнопку отправки.
Мы получаем выходные данные из action_cookie_main.jsp, где переменные хранятся в файлах cookie на стороне клиента.