day_05cookie+session+application

阅读更多

十二月 20, 2015 19:59:17

 

处理cookie

      1.Http协议的无连接性要求一种保存C/S间状态的机制

      2.Coolie:保存到客户端的一个文本文件,与特定客户无关

      3.Cookie以“名--值”对的形式保存数据

      4.创建Cookie:new Cookie(name,value)

      5.可以使用Cookie 的serXXX方法来设定一些相应的值

         5.1 setName(String name)/getName()

         5.2 setValue(String value)/getValue()

         5.3 setMaxAge(int age)/getMaxAge()

         5.4 利用HttpServletResponse的addCookie(Cookie)方法将它设置到客户端

         5.5 利用HttpServletRequest的getCookies()方法来读取客户端的所有的cookie。

 

 

一、cookie原理:

基本原理:

1.服务器可以向客户端写的内容,

2.只能是文本文档

3.客户端可以阻止不让写

4.只能拿自己的webapp写的东西(一个浏览器的标记)

 

     是服务器在本地写的内容,可以进行阻止写入cookie,

在internet选项-->隐私-->高(阻止所有cookie)

 

cookie在本地的地址:

  C盘.....C:\Documents and Settings\Administrator\Cookies

 

Documents and Settings\Administrator\Cookies

 

 

server向client端的cookies;

1.如果设置周期时,写在本地;

2.未设置或者为-1时,是写在client端的内存里;关掉本窗口,就没了。

 

 

 

5.cookie分为两种

    属于窗口/子窗口

    属于文本

6.一个servlet/jsp设置的cookies能够被同一个路径下面或者子路径下面的servlet/jsp读到(路径=url)

(路径!=真实文件路径)

 

二、cookie代码案例

SetCookies.java

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; 
/**
 * 设置Cookie到客户端
 * @author jukey
 *
 */
public class SetCookies extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 向客户端写入Cookie,共6个
        for(int i = 0; i < 3; i++) {
            // 3个没设置时间的Cookie,属于本窗口及其子窗口
            Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i);
            response.addCookie(cookie);
            // 以下3个Cookie设置了时间(3600秒,1小时,属于文本,别的窗口也可以访问到这些Cookie
            cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i);
            cookie.setMaxAge(3600);
            response.addCookie(cookie);
        }
        
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        String title = "Setting Cookies";
        out.println("设置Cookie"
                + "" + title + "
" + "There are six cookies associates with this page.
" + "to see them,visit the \n" + "ShowCookies servlet" + ""); } }

 ShowCookies

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; 
/**
 * 读取客户端的Cookies
 */
public class ShowCookies extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setContentType("text/html;charset=gb2312");
        PrintWriter pw = response.getWriter();
        String title = "Active Cookies";
        pw.println("init");
        pw.println("读取客户端"
                + title
                + "\n" + "\n"
                + "\n" + "\n"
                        + "\n");
            }
        }
        pw.println("
Cookie NameCookie Value" + "
"); // 读取客户端的所Cookie Cookie[] cookies = request.getCookies(); if(cookies != null) { Cookie cookie; for(int i = 0; i < cookies.length; i++) { cookie = cookies[i]; pw.println("
" + cookie.getName() +"" + cookie.getValue() +"
\n"); } }

 web.xml



  
    HelloServlet
    HelloServlet
  
  
    ServletLifeCycle
    ServletLifeCycle
  
  
    ThreeParams
    ThreeParams
  
  
    ShowParameters
    ShowParameters
  
  
    This is the description of my J2EE component
    This is the display name of my J2EE component
    SetCookies
    SetCookies
  
  
    This is the description of my J2EE component
    This is the display name of my J2EE component
    ShowCookies
    ShowCookies
  

  
    HelloServlet
    /httpServlet
  
  
    ServletLifeCycle
    /ServletLifeCycle
  
  
    ThreeParams
    /ThreeParams
  
  
    ShowParameters
    /servlet/ShowParameters
  
  
    SetCookies
    /servlet/SetCookies
  
  
    ShowCookies
    /servlet/ShowCookies
  

 结果:

本地cookies存在的

Persistent-Cookie-0

Cookie-Value-P0

localhost/TestServlet01/servlet/

1536

1530043264

30489391

4193558928

30489382

*

Persistent-Cookie-1

Cookie-Value-P1

localhost/TestServlet01/servlet/

1536

1530043264

30489391

4193558928

30489382

*

Persistent-Cookie-2

Cookie-Value-P2

localhost/TestServlet01/servlet/

1536

1530043264

30489391

4193558928

30489382

*

 

三、会话跟踪 Session

  3.1 在某段时间一连串客户端与服务器端的交易

  3.2 在Jsp/Servlet中,如果浏览器不支持Cookie,可以通过URL重写来实现,就试讲一些额外数据追加到表示会话的每个URL末尾,

        服务器在该标识符与其存储的有关的该会话的数据之间建立关联。

         如:  hello.jsp?jsessionid=1234

  3.3 可以通过程序来终止一个会话。如果客户端在一定时间内没有操作,服务器会自动终止会话。

  3.3 通过HttpSession来读写Session

 

规则:

   1.如果浏览器支持Cookie,创建Session的还好会把SessionID保存在Cookie里

    2.如果不支持Cookie,必须自己变成使用URL重写的方式实现Session

         2.1 response.encodeURL()

               转码

               URL后面加入SessionId

         2.2Session不像Cookie拥有路径访问的问题

             同一个application下的servet/jsp可以共享同一个session,前提是同一客户端窗口。

 

session是和窗口关联起来的,窗口关了这个sessionid就没了

 

 

 

HttpServletRequest中的Session管理方法

1.getRequestSessionId():

     返回随客户端请求到来的会话ID。可能与当前的会话ID相同,也可能不同。

 2.getSession(boolean isNew): 如果会话已存在一个HttpSession,如果不存在并且isNew()为true,则会创建一个HttpSession。

 3.isRequestedSessionIdFromCookie():当前的session ID如果是从cookie获得,为true。

 4.isRequestedSessionIdValid(): 如果客户端的会话ID代表的是有效会话,则返回true。否则(比如,会话国企或根本不存在),返回false。

 5.HttpSession的常用方法:

     5.1getAtrributeNames()/getAttribute()

     5.2getCreateTime()

     5.3getId()

     5.4 getMaxInactiveInterval()

     5.5invalidate()

     5.6 isNew()

     5.7 setAttribuye()

     5.8 setMaxInactivateInterval() 

 

refresh后jsessionid=45F4C3391CB26DAE6B28C104B6571A12

 

 out.println("refresh");

 

http://localhost:8080/TestServlet01/servlet/SessionInfoServlet;jsessionid=45F4C3391CB26DAE6B28C104B6571A12

 

代码案例

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; 
/**
 * 演示Servlet API中的session管理机制(常用方法)
 * @author jukey
 *
 */
public class SessionInfoServlet extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Returns the current session associated with this request, or if the request does not have a session, creates one. 
        HttpSession mySession = request.getSession(true);
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String title = "Session Info Servlet";
        out.println("");
        out.println("");
        out.println("Session Info Servlet");
        out.println("");
        out.println("");
        out.println("

Session Infomation

"); // Returns true if the client does not yet know about the session or if the client chooses not to join the session. out.println("New Session:" + mySession.isNew() + "
"); // Returns a string containing the unique identifier assigned to this session. out.println("Session Id:" + mySession.getId() + "
"); // Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. out.println("Session Create Time:" + new Date(mySession.getCreationTime()) + "
"); out.println("Session Last Access Time:" + new Date(mySession.getLastAccessedTime()) + "
"); out.println("

Request Infomation

"); // Returns the session ID specified by the client. out.println("Session Id From Request:" + request.getRequestedSessionId() + "
"); // Checks whether the requested session ID came in as a cookie. out.println("Session Id Via Cookie:" + request.isRequestedSessionIdFromCookie() + "
"); // Checks whether the requested session ID came in as part of the request URL. out.println("Session Id Via URL:" + request.isRequestedSessionIdFromURL() + "
"); // Checks whether the requested session ID is still valid. out.println("Valid Session Id:" + request.isRequestedSessionIdValid() + "
"); out.println("refresh"); out.println(""); out.close(); } }

 ShowSession

 

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; 
/**
 * Session追踪
 * 如果浏览器支持Cookie,创建Session的时候会把SessionId保存在Cookie中
 * 否则必须自己编程使用URL重写的方式实现Session:response.encodeURL()
 * @author jukey
 *
 */ 
public class ShowSession extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        String str = "Session Tracking Example";
        String heading;
        
        // 如果会话已经存在,则返回一个HttpSession;否则创建一个新的
        HttpSession session = request.getSession(true);
        // 从当前session中读取属性accessCount的值
        Integer accessCount = (Integer)session.getAttribute("accessCount");
        if(accessCount == null) {
            accessCount = new Integer(0);
            heading = "Welcome newUser";
        } else {
            heading = "Welcome Back";
            accessCount = new Integer(accessCount.intValue() + 1);
        }
        // 向当前session中插入键(key,属性)值(value)对
        // Binds an object to this session, using the name specified.
        session.setAttribute("accessCount", accessCount);
        
        out.println("Session追踪"
                + "" + heading + "
" + "

Information on Your Session


" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + ""); } }

 四、Application

4.1 用于保存整个WebApplication的生命周期内都可以访问的数据

4.2 在API中表现为ServletContext

4.3通过HttpServlet的getServletContext方法可以拿到

4.4通过ServletContext的get/setAttribute方法取得/设置相关属性

 

 

http://localhost:8080/TestServlet01/servlet/TestServletContext

 

 

import java.io.IOException;
import java.io.PrintWriter; 
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
/**
 * Application测试
 * 用于保存整个web应用的生命周期内都可以访问的数据
 * 可供多个不同窗口访问,可作为某一页面被总共访问次数的计数器(比如网站首页的访问量)
 * @author jukey
 *
 */
public class TestServletContext extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        
        // Returns a reference to the ServletContext in which this servlet is running. 
        ServletContext application = this.getServletContext();
        // 从当前application中读取属性accessCount的值
        Integer accessCount = (Integer)application.getAttribute("accessCount");
        if(accessCount == null) {
            accessCount = new Integer(0);
        } else {
            accessCount = new Integer(accessCount.intValue() + 1);
        }
        // 向当前application中插入键(key,属性值(value对
        application.setAttribute("accessCount", accessCount);
        
        out.println("ServletContext测试
" + "
\n" + ""); } }

 web.xml


    This is the description of my J2EE component
    This is the display name of my J2EE component
    TestServletContext
    TestServletContext
  

    TestServletContext
    /servlet/TestServletContext
  

 

Servlet类本身位于包中的情况 

 

HelloWorldServlet2

http://localhost:8080/TestServlet01/servlet/HelloWorldServlet2

package com.bjsxt.servlet; 
import java.io.IOException;
import java.io.PrintWriter; 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
/**
 * Servlet类本身位于包中的情况
 * classes中要class文件及其各级目录一起放置
 * web中如下设置:com.bjsxt.servlet.HelloWorldServlet2
 * @author jukey
 *
 */
public class HelloWorldServlet2 extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        out.println("Hello World!");
        
    } 
} 

 web.xml

 
    This is the description of my J2EE component
    This is the display name of my J2EE component
    HelloWorldServlet2
    com.bjsxt.servlet.HelloWorldServlet2
  
 
    HelloWorldServlet2
    /servlet/HelloWorldServlet2
  

 星期日, 十二月 20, 2015 22:28:38

你可能感兴趣的:(cookie原理,会话跟踪,Session,Application)

Info TypeValue" + "
" + "
ID" + session.getId() +"
CreatTime" + new Date(session.getCreationTime()) +"
LastAccessTime" + new Date(session.getLastAccessedTime()) +"
Number of Access" + accessCount +"
" + accessCount +"