学习目标:
JSP使用cookie
学习内容:
什么是Cookie:Cookie是一种浏览器和服务端交互数据的方式,Cookie由服务端创建但是不保留在服务器而是保留在本地,下次再访问时浏览器就会把Cookie发给服务端
Cookei的例子:如登录某些网站时会询问你是否保存登录状态,保存了就会某段时间不需要再输入账号密码,就是通过Cookie实现
学习时间:
学习产出:
setCookie.jsp:
<%@ page import="java.net.URLEncoder" %><%--
Created by IntelliJ IDEA.
User: Magic Book
Date: 2020/12/16
Time: 20:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>设置Cookie</title>
</head>
<body>
<%
//创建Cookie
Cookie c1 = new Cookie("name1", "zhangsan");
//设置Cookie的保留时间,如果为0则不会保存该Cookie
c1.setMaxAge(60*60*24);
// 设置访问路径,如果为("/asda"),则只有当路径为/asda才会提交Cookie
c1.setPath("/");
Cookie c2 = new Cookie("name2","lisi");
c2.setMaxAge(60*60*24);
c2.setPath("/");
Cookie c3 = new Cookie("name3","wangwu");
c3.setMaxAge(60*60*24);
c3.setPath("/");
//通过response将Cookie保存在本地
response.addCookie(c1);
response.addCookie(c2);
response.addCookie(c3);
%>
<a href="getCookie.jsp">获取Cookie</a>
</body>
</html>
getCookie.jsp:
<%@ page import="java.net.URLEncoder" %><%--
Created by IntelliJ IDEA.
User: Magic Book
Date: 2020/12/16
Time: 21:02
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>获取Cookie</title>
</head>
<body>
<%
Cookie []cookies = request.getCookies();
out.println(cookies.length);
if(null!=cookies){
for(int i =0;i<cookies.length;i++){
out.println("i:"+i+cookies[i].getName()+":"+ cookies[i].getValue()+"<br>");
}
}
%>
</body>
</html>