search
HomeJavajavaTutorialHow 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 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");

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!

Statement
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
How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

How does platform independence simplify deployment of Java applications?How does platform independence simplify deployment of Java applications?May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

How has Java's platform independence evolved over time?How has Java's platform independence evolved over time?May 02, 2025 am 12:12 AM

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools