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

How to use cookies in JSP? (code example)

青灯夜游
青灯夜游Original
2019-02-11 12:53:032978browse

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中文网","//m.sbmmt.com/);
       // 设置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