cookie 是一种发送到客户浏览器的文本串句柄,并保存在客户机硬盘上,可以用来在某个WEB站点会话间持久的保持数据。
一、:Cookie的发送和接收
发送端代码,AServlet.java,通过addCookie(cookie)将我们预先设定的好的Cookie发送给浏览器
import java.io.IOException; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //演示发送cookie(头)到浏览器 public class AServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //明白原理的写法: //response.setHeader("set-Cookie", "name=tom"); //使用封装好的代码 //创建cookie对象 => 封装键值对 Cookie cookie = new Cookie("name",URLEncoder.encode("汤姆","UTF-8")); //将cookie添加到response中 => 添加响应头 response.addCookie(cookie); } }接收端代码,BServlet.java,打印时候分别打印编码值和其解码值
import java.io.IOException; import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //演示取出浏览器发送过来的cookie public class BServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获得浏览器发送的所有cookie Cookie[] cookies = request.getCookies(); Cookie nameCookie = null; //遍历,找到我们要找的cookie if(cookies!=null){ for(Cookie c : cookies){ if("name".equals(c.getName())){ //找到了 nameCookie = c; } } } if(nameCookie!=null){ System.out.println("浏览器发送的cookie==>" + nameCookie.getName()+":"+nameCookie.getValue()); System.out.println("浏览器发送的cookie==>" + nameCookie.getName()+":"+URLDecoder.decode(nameCookie.getValue(), "UTF-8")); }else{ System.out.println("没有找到namecookie"); } } }先执行AServlet,再执行BServlet,其打印结果如下
浏览器发送的cookie==>name:%E6%B1%A4%E5%A7%86 浏览器发送的cookie==>name:汤姆
二、:设置Cookie的有效时间和路径
设置时间是按秒来计算的
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie c = new Cookie("name","jerry"); //设置cookie的有效时间 c.setMaxAge(60*60*24*7*2);//告诉浏览器保存2周 //c.setMaxAge(-1);// -1代表 在会话结束时删除cookie(默认情况) //c.setMaxAge(0);// 通常用于删除已经存在的cookie.使用一个寿命为0的cookie,覆盖要删除的cookie //设置Cookie的路径 c.setPath("/day09-cookie/ABC"); response.addCookie(c); } }
三、:通过Cookie显示浏览历史
1、首先需要有一个jsp的交互展示页面list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <a href="/day09-cookie/EServletname=dell" >dell</a><br> <a href="/day09-cookie/EServletname=lenovo" >lenovo</a><br> <a href="/day09-cookie/EServletname=hasee" >hasee</a><br> <a href="/day09-cookie/EServletname=hp" >hp</a><br> <a href="/day09-cookie/EServletname=apple" >apple</a><br> <a href="/day09-cookie/EServletname=acer" >acer</a><br> 浏览历史:${cookie.history.value} </body> </html>2、编写一个CookieUtils.java的工具类来遍历Cookie数组
package cn.itcast.f_history; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; public class CookieUtils { // 通过名字获得cookie,通过遍历一个cookie数组来获得对应名字的cookie public static Cookie getCookieByName(HttpServletRequest request,String name){ Cookie cookie = null; Cookie[] cookies = request.getCookies(); if(cookies!=null){ for(Cookie c: cookies){ if(name.equals(c.getName())){ cookie = c; } } } return cookie; } }3、接收到Cookie并处理,Cookie名字叫history,如果history没有的话再加上对应的品牌
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.获得参数 String name = request.getParameter("name"); // 2.获得Cookie Cookie history = CookieUtils.getCookieByName(request, "history"); if(history!=null){ // //存在 => 修改cookie加上现在浏览器的品牌 => dell,hp,lenvo if(!history.getValue().contains(name)){ history = new Cookie("history",history.getValue()+","+name); } }else{ // //不存在 => 创建cookie history = new Cookie("history",name); } // 3.将cookie发送会浏览器 response.addCookie(history); // 4.重定向到列表页面 response.sendRedirect("/day09-cookie/history/list.jsp"); } }
四、:通过Cookie记住用户名
1、首先也是需要一个login.jsp,其中最为关键的是checkbox中的当cookie.remember不等于null时,checked=checked,也就是返回一个yes
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="/day09-cookie/FServlet" > 用户名:<input type="text" name="name" value="${cookie.remember.value}" /> <font color="red">${requestScope.error}</font> <br> 密码:<input type="text" name="password" /><br> <input type="checkbox" name="remember" value="yes" ${cookie.remember==null"":"checked=checked"} />记住用户名<br> <input type="submit" value="登录" /> </form> </body> </html>2、创建Cookie,添加要需要保存的用户名
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.获得用户名密码 String name = request.getParameter("name"); // 2.校验用户名密码 if(name==null || "".equals(name.trim())){ // //失败=> 转发到表单页面,并提示错误 //给request添加error属性,属性叫做“请输入用户名” request.setAttribute("error", "请输入用户名!"); request.getRequestDispatcher("/remember/login.jsp").forward(request, response); return; } // 3.创建cookie 添加要保存的用户名, Cookie c = new Cookie("remember", name); // 4.查看记住用户名是否被选中 String remember = request.getParameter("remember"); if("yes".equals(remember)){ // 选中 => 设置保存时间为2周 c.setMaxAge(60*60*24*7*2); }else{ // //没选中=>设置保存事件为0 c.setMaxAge(0); } // 5.添加到响应中 response.addCookie(c); // 6.重定向到成功页面 response.sendRedirect("/day09-cookie/index.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
五、:Session简单介绍
session其实指的就是访问者从到达某个特定主页到离开为止的那段时间。 Session其实是利用Cookie进行信息处理的,当用户首先进行了请求后,服务端就在用户浏览器上创建了一个Cookie,当这个Session结束时,其实就是意味着这个Cookie就过期了。
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class AServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //参数类型是boolean型 //true=> 无论如何都要获得session //false => 如果没有sessionID ,不会获得session //request.getSession(true); HttpSession session = request.getSession();//相当于上面的方法 填写true //session 的操作 // session.setAttribute(arg0, arg1) // session.getAttribute(arg0) // session.getAttributeNames() // session.removeAttribute(arg0) //session中可以存放登录状态 } }Session中的一些方法
import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class BServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); System.out.println("session.isNew()"+session.isNew());// 判断session是否 是新的. System.out.println("session.getCreationTime()"+new Date(session.getCreationTime()));//获得session的创建时间 System.out.println("session.getId()"+session.getId());//获得session的id System.out.println("session.getLastAccessedTime()"+new Date(session.getLastAccessedTime()));//获得最后一次的访问时间 System.out.println("session.getMaxInactiveInterval()"+session.getMaxInactiveInterval());// 获得session的最大有效时间 //session.setMaxInactiveInterval(60);//设置session的最大有效时间为60秒 session.invalidate();//*** 立即让session销毁. } }
六、:Cookie和Session区别
(1)Cookie数据存放在客户的浏览器上,session数据放在服务器上
(2)Cookie不是很安全,别人可以分析存放在本地的Cookie并进行Cookie欺骗,如果主要考虑到安全应当使用session
(3)Session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能,如果主要考虑到减轻服务器性能方面,应当使用Cookie
(4)单个Cookie在客户端的限制是3K,就是说一个站点在客户端存放的Cookie不能3K。
(5)所以:将登陆信息等重要信息存放为SESSION;其他信息如果需要保留,可以放在Cookie中
- 顶
- 1
- 踩
- 0