`

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("<html><head><title>设置Cookie</title></head>"
                + "<body>" + title + "<br>"
                + "There are six cookies associates with this page.<br>"
                + "to see them,visit the <a href=\"ShowCookies\">\n"
                + "<code>ShowCookies</code> servlet</a>"
                + "</body></html>");
    } 
} 

 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("<html><head><title>读取客户端</title></head>"
                + title
                + "\n" + "<table border=1 align=center>\n"
                + "<TH>Cookie Name<TH>Cookie Value" + "<br>");
        
        // 读取客户端的所Cookie
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Cookie cookie;
            for(int i = 0; i < cookies.length; i++) {
                cookie = cookies[i];
                pw.println("<tr>\n" + "<td>" + cookie.getName() +"</td>\n"
                        + "<td>" + cookie.getValue() +"</td></tr>\n");
            }
        }
        pw.println("</table>\n<body><html>");
    } 
} 

 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>ServletLifeCycle</servlet-name>
    <servlet-class>ServletLifeCycle</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>ThreeParams</servlet-name>
    <servlet-class>ThreeParams</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>ShowParameters</servlet-name>
    <servlet-class>ShowParameters</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>SetCookies</servlet-name>
    <servlet-class>SetCookies</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ShowCookies</servlet-name>
    <servlet-class>ShowCookies</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/httpServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ServletLifeCycle</servlet-name>
    <url-pattern>/ServletLifeCycle</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ThreeParams</servlet-name>
    <url-pattern>/ThreeParams</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ShowParameters</servlet-name>
    <url-pattern>/servlet/ShowParameters</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>SetCookies</servlet-name>
    <url-pattern>/servlet/SetCookies</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ShowCookies</servlet-name>
    <url-pattern>/servlet/ShowCookies</url-pattern>
  </servlet-mapping>
</web-app>

 结果:

本地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("<a href=" + response.encodeURL("SessionInfoServlet") + ">refresh</a>");

 

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("<html>");
        out.println("<head>");
        out.println("<title>Session Info Servlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3>Session Infomation</h3>");
        
        // 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() + "<br>");
        // Returns a string containing the unique identifier assigned to this session.
        out.println("Session Id:" + mySession.getId() + "<br>");
        // 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()) + "<br>");
        out.println("Session Last Access Time:" + new Date(mySession.getLastAccessedTime()) + "<br>");
        
        out.println("<h3>Request Infomation</h3>");
        // Returns the session ID specified by the client.
        out.println("Session Id From Request:" + request.getRequestedSessionId() + "<br>");
        // Checks whether the requested session ID came in as a cookie. 
        out.println("Session Id Via Cookie:" + request.isRequestedSessionIdFromCookie() + "<br>");
        // Checks whether the requested session ID came in as part of the request URL. 
        out.println("Session Id Via URL:" + request.isRequestedSessionIdFromURL() + "<br>");
        // Checks whether the requested session ID is still valid. 
        out.println("Valid Session Id:" + request.isRequestedSessionIdValid() + "<br>");
        
        out.println("<a href=" + response.encodeURL("SessionInfoServlet") + ">refresh</a>");
        out.println("</body></html>");
        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("<html><head><title>Session追踪</title></head>"
                + "<body>" + heading + "<br>"
                + "<h2>Information on Your Session</h2><br>"
                + "\n" + "<table border=1 align=center>\n"
                + "<TH>Info Type<TH>Value" + "<br>"
                + "<tr>\n" + "<td>ID</td>\n"
                + "<td>" + session.getId() +"</td></tr>\n"
                + "<tr>\n" + "<td>CreatTime</td>\n"
                + "<td>" + new Date(session.getCreationTime()) +"</td></tr>\n"
                + "<tr>\n" + "<td>LastAccessTime</td>\n"
                + "<td>" + new Date(session.getLastAccessedTime()) +"</td></tr>\n"
                + "<tr>\n" + "<td>Number of Access</td>\n"
                + "<td>" + accessCount +"</td></tr>\n"
                + "</body></html>");
    } 
} 

 四、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("<html><head><title>ServletContext测试</title></head><br>"
                + "<body><td>" + accessCount +"</td>\n"
                + "</body></html>");
        
    } 
} 

 web.xml

<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>TestServletContext</servlet-name>
    <servlet-class>TestServletContext</servlet-class>
  </servlet>
<servlet-mapping>
    <servlet-name>TestServletContext</servlet-name>
    <url-pattern>/servlet/TestServletContext</url-pattern>
  </servlet-mapping>

 

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中如下设置:<servlet-class>com.bjsxt.servlet.HelloWorldServlet2</servlet-class>
 * @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

 <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>HelloWorldServlet2</servlet-name>
    <servlet-class>com.bjsxt.servlet.HelloWorldServlet2</servlet-class>
  </servlet>
 <servlet-mapping>
    <servlet-name>HelloWorldServlet2</servlet-name>
    <url-pattern>/servlet/HelloWorldServlet2</url-pattern>
  </servlet-mapping>

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

0
1
分享到:
评论

相关推荐

    Asp.net中实现同一用户名不能同时登陆(单点登陆)

    string cookieValue = now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString(); // 将用户的 ...

    JavaWeb Session 会话管理实例详解

    但是,通过在URL中携带Session ID,可以在不同浏览器或无Cookie环境下实现跨会话跟踪。 在Servlet中,我们可以使用 `HttpServletRequest.getSession()` 方法获取或创建Session对象。通过 `setAttribute(String name...

    java web过滤器案列

    这个过程中可能涉及到session invalidate()方法的调用,以及与数据库交互来更新用户的登录状态。 **过滤器处理乱码问题** 在Java Web开发中,字符编码问题经常出现,尤其是处理中文字符时。过滤器可以用来解决这个...

    ASP.NET常用代码

    EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName ); //写入事件日志 eventLog.WriteEntry(messageText, ...

    高级软件人才培训专家-day12-SpringBootWeb登录认证

    3. **状态管理**:可以使用JWT(JSON Web Token)来实现无状态的会话管理,这样可以避免使用Cookie和Session。 4. **前端集成**:前端需要与后端进行良好的交互,包括表单验证、错误信息展示等。 #### 五、总结 本...

    JSTL标签库

    - **默认搜索顺序**: JSP引擎默认按照`page`、`request`、`session`、`application`的作用域顺序查找变量。 **1.2 指定作用域** - **示例与含义**: - `${pageScope.user.name}`: 从`page`范围内获取`user`对象并...

    java面试题

    - `Cookie`和`Session`分别用于客户端和服务器端存储会话信息,Session依赖于Cookie,但更安全。 - JSP的`&lt;jsp:include&gt;`和`&lt;%@ include %&gt;`用于包含外部文件,前者运行时包含,后者编译时包含。 11. **J2EE相关...

    JSTL和EL表达式的部门例子

    EL表达式的语法通常为`${expression}`,它会根据表达式中的关键字在不同的作用域(page、request、session、application)中查找对应的值。例如,`${user.name}`会尝试在所有作用域中寻找名为`user`的对象并返回其`...

    2021-2022计算机二级等级考试试题及答案No.4574.docx

    ASP.NET提供了多个内置对象,包括Response、Request、Server、Application、Session和Cookie,这些对象用于处理HTTP请求、响应、服务器操作、全局应用程序状态、用户会话状态以及HTTP Cookie。在Java Swing中,...

    计算机网络第六版答案

    24. Application-layer message: data which an application wants to send and passed onto the transport layer; transport-layer segment: generated by the transport layer and encapsulates application-layer...

    一些一页纸的总结

    - **Day**: 返回日期中的天数。 - **FormatDateTime**: 格式化日期和时间。 - **Hour**: 返回时间中的小时数。 - **Minute**: 返回时间中的分钟数。 - **Month**: 返回日期中的月份。 - **MonthName**: 返回...

    JAVA笔试题,面试题(吐血推荐)

    4. **Cookie和Session的作用**:Cookie用于在客户端保存用户信息,Session则在服务器端保存用户状态信息。Session通常比Cookie更安全。 5. **Jsp中包含外部文件**:可以使用`&lt;%@ include file="filename"%&gt;`或`...

    ICS delphixe10源码版

    .\Samples\delphi\BroswerDemo Delphi Win32/Win64 Web Browser sample application (all Delphi versions) .\Samples\delphi\BroswerDemo\Resources Resource file, web pages and movie linked into browser demo ...

Global site tag (gtag.js) - Google Analytics