How to use cookies in JSP? (code example)
A cookie is a small piece of information stored on the user's computer; the web server will use the cookie to identify the user the next time they visit. The following article will give you a brief understanding of Cookies and introduce how to use JSP to handle Cookies. I hope it will be helpful to you. [Video tutorial recommendation: JSP tutorial]
How cookies work
Cookie will be stored on the user's computer in the form of a string of [key|value] pairs. Additionally, cookies have properties such as domain, path, and timeout.
Every time a user visits a website with cookies enabled, the web server adds extra data to the HTTP headers and responds to the web browser. The web browser will also send the cookie in the HTTP request header to the web server the next time the user visits the same site again.
Users can also disable cookies in web browsers that support the cookie disabling function, such as Firefox, IE...
How to use cookies in JSP ?
JSP provides an API that allows efficient use of cookies through objects of class javax.servlet.http.Cookie. Let's briefly introduce how to use cookies in JSP.
1. Use JSP to set Cookie
Using JSP to set Cookie can be divided into three steps:
1), create a Cookie object:
You need to call the Cookie constructor, for example:
Cookie cookie = new Cookie("key","value");
Note: Cookies exist in the form of key-value pairs, so use the cookie name and value as parameters (they are both strings).
Note: Cookie names and values cannot contain spaces or the following characters:
[ ] ( ) = , " / ? @ : ;
2), Set validity period
Cookies have their own life cycle, called expiration time . If the cookie's timeout is not set, it will be removed when the user closes the web browser.
We can call the setMaxAge() method to set the validity period of the cookie, that is, how long (in seconds) it is valid.
Example: Set the validity period to 24 hours, you can set it like this
cookie.setMaxAge(60*60*24);
3), send the cookie to the HTTP response header
You need to call the response.addCookie() method Add cookies to HTTP response headers. Example:
response.addCookie(cookie);
Simple example: Send cookie from web server
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="javax.servlet.http.Cookie"%> <!DOCTYPE html> <html> <head> <title>设置Cookie</title> </head> <body> <% // 编码,解决中文乱码 String str = URLEncoder.encode(request.getParameter("name"),"utf-8"); // 设置 name 和 url cookie Cookie cookie = new Cookie("php中文网","http://www.php.cn/); // 设置cookie过期时间为24小时。 cookie.setMaxAge(60*60*24); // 在响应头部添加cookie response.addCookie(cookie); %> </body> </html>
Read Cookie using JSP
To read cookie from HTTP request, First, call the getCookies() method of the request object, which returns the list of available cookies in the request header; or use the getName() method and getValue() method to obtain the name and value of each cookie. All these cookies can then be browsed. The following is an example of using the getCookies() method to read cookie information:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="javax.servlet.http.Cookie"%> <html> <head> <title>读取Cookie</title> </head> <body> <% Cookie[] list = request.getCookies(); if(list != null){ for(int i = 0; i < list.length;i++){ out.println(list[i].getName() + ":" + list[i].getPath()); } } %> </body> </html>
Delete existing cookies using JSP
If you want to delete the cookie that has been sent to the web browser For existing cookies, you can set their validity period to zero using the setMaxAge() method of the cookie object.
The steps are as follows:
● Get an existing cookie and store it in the Cookie object.
● Use the setMaxAge() method to set the cookie validity period to 0.
Example: The following is an example to delete all cookies.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="javax.servlet.http.Cookie"%> <!DOCTYPE html> <html> <head> <title>删除cookie</title> </head> <body> <% Cookie[] list = request.getCookies(); if (list != null) { for (int i = 0; i < list.length; i++) { list[i].setMaxAge(0); out.println("cookie:" + list[i].getName() + "已删除"); } } %> </body> </html>
The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to use cookies in JSP? (code example). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

Implementation steps: 1. Introduce the JSTL tag library into the JSP page; 2. Obtain data from the database; 3. Paging the data; 4. Display the paging navigation bar in the page; 5. Display the number according to the current page number and each page. , just get the corresponding data from the paging data and display it on the page.

The difference between jsp and html: 1. Operating mechanism; 2. Purpose; 3. Relationship with Java; 4. Function; 5. Relationship with back-end; 6. Speed; 7. Maintainability and scalability; 8. Learning and use Difficulty; 9. File suffixes and identification tools; 10. Community and support; 11. Security. Detailed introduction: 1. Operating mechanism. HTML is a markup language, mainly used to describe and define the content of web pages. It runs on the client and is interpreted and executed by the browser. JSP is a dynamic web page technology that runs on the server side, etc. wait.

Common problems and solutions for cookie settings, specific code examples are required. With the development of the Internet, cookies, as one of the most common conventional technologies, have been widely used in websites and applications. Cookie, simply put, is a data file stored on the user's computer that can be used to store the user's information on the website, including login name, shopping cart contents, website preferences, etc. Cookies are an essential tool for developers, but at the same time, cookie settings are often encountered

In our daily use of computers and the Internet, we are often exposed to cookies. A cookie is a small text file that saves records of our visits to the website, preferences and other information. This information may be used by the website to better serve us. But sometimes, we need to find cookie information to find the content we want. So how do we find cookies in the browser? First, we need to understand where the cookie exists. in browser
