Home Java javaTutorial How to use cookies in JSP? (code example)

How to use cookies in JSP? (code example)

Feb 11, 2019 pm 12:53 PM
cookie jsp

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 to use cookies in JSP? (code example)

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");
Copy after login

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:

[ ] ( ) = , " / ? @ : ;
Copy after login

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);
Copy after login

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);
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

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.

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

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.

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

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.

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

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.

How to implement jsp paging function How to implement jsp paging function Mar 04, 2024 pm 04:40 PM

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.

What is the difference between jsp and html What is the difference between jsp and html Jan 09, 2024 am 10:46 AM

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.

Frequently Asked Questions and Solutions about Cookie Settings Frequently Asked Questions and Solutions about Cookie Settings Jan 19, 2024 am 09:08 AM

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

How to find cookies in your browser How to find cookies in your browser Jan 19, 2024 am 09:46 AM

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

See all articles