Create and get cookie s

Create and get cookie s Producer: heart and soul Cookie: in the Internet, a cookie is a small piece of text information generated on a web server and ...
Create and get cookie s Producer: heart and soul Cookie: in the Internet, a cookie is a small piece of text information generated on a web server and sent to a browser. Cookies can be used to identify users, record user names and passwords, track duplicate users, etc. The browser saves the cookie in the form of key/value to a specified directory of the client.

getCookies(): get the collection of all cookie objects
getName(): get the cookie with the specified name
getValue(): get the value of cookie object Test page save and get cookie page
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.net.URLDecoder" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>adopt cookie Save and read user login information</title> </head> <body> <% Cookie[] cookies = request.getCookies(); String user = ""; String date = ""; if(cookies != null){ for(int i =0;i<cookies.length;i++){ if(cookies[i].getName().equals("mrCookie")){ user = URLDecoder.decode(cookies[i].getValue().split("#")[0]); date = cookies[i].getValue().split("#")[1]; } } } if( "".equals(user) && "".equals(date) ){ %> //Hello tourists, welcome to visit for the first time! <form action="index1.jsp" method="post"> //Please enter a name: < input name = "user" type = "text" value = "" > <input type="submit" value="Determine"> </form> <% }else{ %> //Welcome to visit again //Your registration time is: <% = date% > <% } %> </body> </html>

Create cookies page

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.net.URLEncoder" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Write in cookie</title> </head> <body> <% String user = URLEncoder.encode(new String(request.getParameter("user").getBytes("ISO-8859-1"),"UTF-8")); Cookie cookie = new Cookie("mrCookie",user+"#"+new java.util.Date().toLocaleString()); cookie.setMaxAge(5); response.addCookie(cookie); %> <%=user %> <script type="text/javascript">window.location.href="index.jsp"</script> </body> </html>

Tips: if the information saved to the cookie includes Chinese, you need to call the encode() method of java.net.URLEncoder class to encode the information saved to the cookie; when reading the contents of the cookie, you need to use the decode() method of java.netURLDecoder class to decode. In this way, Chinese information can be successfully written to the cookie.

31 December 2020, 04:14 | Views: 4718

Add new comment

For adding a comment, please log in
or create account

0 comments