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
jsp是属于前端还是后端jsp是属于前端还是后端Jan 28, 2023 pm 06:23 PM

jsp属于后端。jsp的本质是一种servlet,而servlet又是服务器端的java应用程序,所以jsp是属于后端的技术。JSP部署于网络服务器上,可响应客户端发送的请求,并根据请求内容动态地生成HTML、XML或其他格式文档的Web网页,然后返回给请求者。JSP技术以Java作为脚本语言,为用户HTTP请求提供服务,并能与服务器上的其它Java程序共同处理复杂的业务需求。

SpringBoot项目如何整合JSPSpringBoot项目如何整合JSPMay 12, 2023 pm 07:40 PM

新建好springboot项目以后目录如下:第一步:在项目的pom文件中加入配置jsp所需要的jar包代码:org.apache.tomcat.embedtomcat-embed-jasperprovided第二步:在main路径下新建目录webapp,在webapp下新建路径WEB-INF,在WEB-INF下新建路径jsp,在这个路径下放置我们要使用的jsp文件第三步:在主配置文件中配置jsp文件的访问路径和后缀代码:spring.mvc.view.prefix=/WEB-INF/jsp/sp

jsp分页功能怎么实现jsp分页功能怎么实现Mar 04, 2024 pm 04:40 PM

实现步骤:1、在JSP页面中引入JSTL标签库;2、从数据库中获取数据;3、对数据进行分页处理;4、在页面中显示分页导航条;5、根据当前页码和每页显示数量,从分页后的数据中获取对应的数据并显示在页面上即可。

jsp和html区别在哪jsp和html区别在哪Jan 09, 2024 am 10:46 AM

jsp和html区别:1、运行机制;2、用途;3、与Java的关系;4、功能;5、与后端的关系;6、速度;7、可维护性和扩展性;8、学习和使用的难易程度;9、文件后缀和识别工具;10、社区和支持;11、安全性。详细介绍:1、运行机制,HTML是一种标记语言,主要用于描述和定义网页的内容,它运行在客户端,由浏览器解释执行,JSP是一种动态网页技术,运行在服务器端等等。

jsp是什么格式的文件jsp是什么格式的文件Jan 24, 2024 pm 04:01 PM

​JSP是一种动态网页技术标准,其文件格式是在传统的网页HTML文件(.htm,.html)中插入Java程序段(Scriptlet)和JSP标记(tag),从而形成JSP文件(*.jsp)。

如何用jsp+mysql实现网页的分页查询如何用jsp+mysql实现网页的分页查询May 30, 2023 pm 03:58 PM

一、实现分页查询的核心sql语句(1)查询数据库的记录总数的sql语句:selectcount(*)from+(表名);(2)每次查询的记录数的sql语句:其中:0是搜索的索引,2是每次查找的条数。select*from表名limit0,2;二、代码实现*上篇写过这两个类,DBconnection类:用于获取数据库连接,Author对象类。这两个类的代码点击连接查看。点击链接查看DBconnection类和Author对象类(1)登录页面:index.jsp。Inserttitlehere用户列

Web开发的Java技术栈:了解Java EE、Servlet、JSP、Spring等常用于Web开发的技术Web开发的Java技术栈:了解Java EE、Servlet、JSP、Spring等常用于Web开发的技术Dec 26, 2023 pm 02:29 PM

JavaWeb开发技术栈:掌握JavaEE、Servlet、JSP、Spring等用于Web开发的技术随着互联网的迅速发展,在当今的软件开发领域,Web应用的开发已经成为一种非常重要的技术需求。而Java作为一种广泛应用的编程语言,其在Web开发领域也有着重要的地位。JavaWeb开发技术栈涉及多项技术,如JavaEE、Servlet、JSP、Spr

jsp中iframe是什么jsp中iframe是什么Aug 24, 2023 pm 04:02 PM

jsp中iframe是一种用于嵌入其他网页或文档的HTML标签,可以实现页面的分割、动态加载、异步加载和跨域访问等功能。它为开发人员提供了更多的灵活性和交互性,可以提高网页的可用性和用户体验。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)