Cookie——Session
来源:互联网 发布:matlab提取矩阵一部分 编辑:程序博客网 时间:2024/06/05 02:11
Cookie Session是跨越编程语言的网站开发的基础知识,对于web application开发的基础。
首先我们知道http协议是面向无连接的,但是很明显在我们日常的网上操作中需要各个网页之间有信息的传递!例如,网上商城的购物车,以及简单的用户登录,这时候就需要cookie 或者session来保存用户的一些信息!
1. Cookie
cookie是保存在客户端的键值对数据,类似于map。 java中通过new cookie(name,value)来创建cookie。 可以通过cookie.setxxx()来设置是cookie的属性。 如果不设置cookie的最大生命周期,则默认生命周期为session,即对应窗口的周期,当窗口不关闭,则在窗口或者子窗口一直可用;如果通过myCookie.setMaxAge(3600)设置,则会持久化到本地硬盘,到生命周期会被删除。
- createCookie
package com.kanbujian.servlet;import java.io.IOException;import java.io.PrintWriter;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 createCookie extends HttpServlet { /** * Constructor of the object. */ public createCookie() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); for(int i=0;i<3;i++){ //cookie 不设置最大生命周期 //默认为session周期,即窗口未关闭之前 Cookie cookie=new Cookie("SessionCookie"+i,"cookievalue"+i); response.addCookie(cookie); //cookie 设置最大生命周期 ,持久化到客户端本地硬盘中生成cookie文件 Cookie myCookie=new Cookie("PersistentCookie"+i,"cookieValue"+i); myCookie.setMaxAge(3600); response.addCookie(myCookie); } PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" <p>我们创建了cookie文件,如果不设置最大生命周期,则默认使用session周期,当浏览器窗口不关闭时,cookie一直起作用;当设置最大生命周期,则持久化客户端本地硬盘上,到达生命周期,则会被删除</p>"); out.println("<a href=\"showCookie\">shwoCookies<a/>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
- showCookie
package com.kanbujian.servlet;import java.io.IOException;import java.io.PrintWriter;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 showCookie extends HttpServlet { /** * Constructor of the object. */ public showCookie() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" <table style=\"width:600px;margin:20px auto\">"); out.print("<tr><th>CookieName</th><th>CookieValue</th></tr>"); Cookie[] cookies=request.getCookies(); if(cookies!=null){ for(int i=0;i<cookies.length;i++){ out.println("<tr><td>"+cookies[i].getName()+"</td><td>"+cookies[i].getValue()+"</td></tr></br>"); } } out.println("</table>"); out.println("<div >"); out.println("<img style=\"margin:20px auto\" src=\"http://i4.tietuku.com/51477eb3e3abf7d4.jpg\">"); out.println("<img style=\"margin:20px auto\" src=\"http://i4.tietuku.com/895ab2864761f029.jpg\">"); out.println("</div>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
2. Session
cookie是保存在客户端上面的,而这样就可能发生服务商不可控或者不可预知的情况,可能浏览器设置不允许cookie或者cookie被清理软件清空等等,所以保存在服务器端的session通常是一个更为可靠的方式! session,会话,表示客户端浏览器和服务器的一次“交流 交易”。 session通过在request.getSession(true)方法获得,当参数为true时表示,当request不存在session则创建一个,若存在,则获得;当参数为false时,当request不存在session并不进行创建操作。
- SessionInfoServlet
package com.kanbujian.servlet;import java.io.IOException;import java.io.PrintWriter;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 SessionInfoServlet extends HttpServlet { /** * Constructor of the object. */ public SessionInfoServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); //getSession()参数为true时,若request存在session,则获得;若request不存在session,则创建一个新的 //当参数为false时,若request存session 则获得;若request不存在session则不生成 HttpSession ClientSession=request.getSession(true); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>Session Information</TITLE></HEAD>"); out.println(" <BODY>"); out.print("<h2>Session Information</h2>"); out.print("SessionID : "+ClientSession.getId()+"</br>"); out.print("Session is New : "+ClientSession.isNew()+"</br>"); //ClientSession.getCreationTime()返回long类型以毫秒为单位,转化为Date类型 out.print("Session create time : "+new Date(ClientSession.getCreationTime())+"</br>"); //最近一次得到session的时间 out.print("Session last access time : "+new Date(ClientSession.getLastAccessedTime())+"</br>"); out.print("<h2>Request Information</h2>"); out.print("Session ID from request : "+request.getRequestedSessionId()+"</br>"); out.print("Session ID via cookie : "+request.isRequestedSessionIdFromCookie()+"</br>"); out.print("Session ID via rewritten URL : "+request.isRequestedSessionIdFromURL()+"</br>"); out.print("valid Session ID : "+request.isRequestedSessionIdValid()+"</br>"); out.println("<p>当Cookie关闭时,通过重写URL实现session!</p>"); out.println("<a href="+response.encodeURL("SessionInfoServlet")+ " >Refresh</a>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); /* * 关于session * session实现的两种方式 * 1.依赖cookie * 如果浏览器支持cookie,则会把sessionID 存在Cookie中, * 可通过SessionInfoServlet,然后showcookie验证 * * 2.URL重写 * 如果浏览器关闭cookie支持,则需要自己编程实现 * response.encodeURL() * 1>可以转码,当URL含有中文 * 2>会在URL后面加入sessionId */ } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
当浏览器开启cookie时,除了第一个生成的cookie是新的,后面sessionID保持不变,唯一标识客户端浏览器
这是默认是通过cookie方式实现了,点击showCookie,可以看到到存在一个cookie,value为SessionID。
当浏览器关闭cookie时,刷新页面,sessionID一直发生变化,则session并没有起到作用。
这是需要通关重写URL的方式
response.encodeURL()
该方法会在URL后面加上sessionID,让服务器读取URL即可获取sessionID,标示浏览器,读取指定session保存的信息
这是cookie关闭,showCookie页面无cookie信息
- showSession
package com.kanbujian.servlet;import java.io.IOException;import java.io.PrintWriter;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 showSession extends HttpServlet { /** * Constructor of the object. */ public showSession() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String heading; HttpSession httpSession=request.getSession(true); //登录次数 Integer AccessCount=(Integer)httpSession.getAttribute("AccessCount"); if(AccessCount==null){ AccessCount =new Integer(0); heading="欢迎,新用户!"; } else{ heading="欢迎回来!"; AccessCount=new Integer(AccessCount.intValue()+1); } httpSession.setAttribute("AccessCount", AccessCount); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>Show Session</TITLE></HEAD>"); out.println(" <BODY>"); out.print("<h2 align=\"center\">the information of your session</h2> "); out.println("<table style=\"margin:20px auto;width:500px\" ><tr><th>Info Type</th><th>Value</th><tr>"); out.println("<tr><td>Session ID</td>"+"<td>"+httpSession.getId()+"</td>"); out.println("<tr><td>Create Time</td>"+"<td>"+new Date(httpSession.getCreationTime())+"</td>"); out.println("<tr><td>Last Access Time</td>"+"<td>"+new Date(httpSession.getLastAccessedTime())+"</td>"); out.println("<tr><td>Number of pervious accesses</td>"+"<td>"+httpSession.getAttribute("AccessCount")+"</td>"); out.println("</table>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
0 0
- Cookie——Session
- Cookie与Session深入理解(一)——Cookie
- Session和Cookie学习笔记—Cookie使用
- 传智播客课程系列-——Cookie、Session
- Servlet——Cookie 和 Session
- Servlet——Cookie 和 Session
- Servlet——Cookie 和 Session
- java web笔记——Cookie&&Session
- Web——Cookie与Session
- Cookie和Session详解——博客地址
- 【DRP】——Cookie和Session
- web前端——session和cookie
- 【JAVA】——cookie和session
- 计算机网络 —— cookie 与 session
- JavaWeb——Cookie,Session学习汇总
- servlet自学——Cookie和Session
- webx—基于cookie的session
- Javaweb学习笔记5—Cookie&Session
- Git 错误集锦
- 快速入手ITOO导入-服务端
- 大数据登陆央视分析春运 数据分析软件继走红
- 用java写关于删除一个字符串的字符以及删除一个字符串与另一个字符串中相同字符的问题
- 计算汽车行驶的方向
- Cookie——Session
- thinkphp验证码错误
- lua学习笔记之五(Lua中的数学库)
- 计算两个GPS坐标的距离 方法一 - C#语言
- c/c++线程--3线程池
- 【点滴】LINUX之find命令
- Halcon10 与 VC++交互,通过picture control显示图像
- URAL 2002. Test Task (阅读理解)
- 【python学习资料】各种python 函数参数定义和解析 --转载自byte_way