www.icesr.com
IT运维工程师的摇篮

Servlet学习(六)Session

与Cookie相似,session也是用来记录数据和状态的。

不同在与,cookie记录数据在客户端,session记录数据在服务器端。通过每个浏览器的特定编号。


(重点)session的两种实现方式:

1. 通过Cookie实现。(如果浏览器设置为支持Cookie,则默认为这种方式)

将session的ID存在Cookie里。

测试程序:

package com.vin.session;

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管理机制(常用方法)
 * 创建一个session
 * @author Pigeon
 *
 */
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();
    }

}

创建了一个session,带有一个唯一的sessionId,储存在cookie里,通过ShowCookies查看。





2. 通过URL重写来实现。(浏览器不支持cookie)

就是将一些额外数据(标志符)追加在表示会话的每个URL末尾,服务器在该标志符与其存储的有关该会话的数据之间,建立对应关联。如hello.jsp?jsessionid=1234

response.encodeURL()

  • 转码
  • URL后加入SessionId
测试程序:
将IE的Cookie禁用,再次运行上面的程序。点击refresh后,发现url后被加上了jsessionid

—————————————————————————————————————————————-
session以“name-value”对的形式在服务器的内存中存储数据
session.getAttribute(String name); session通过name拿到value
session.setAttribute(String name, Object value); session设置名值对。
注意:name永远是String,value是Object,因此需要类型转换。
package com.vin.session;

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>");
    }

}

结果:




每次刷新,number of access +1。


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	version="2.5">

	<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  	</welcome-file-list>

	<servlet>
		<servlet-name>HW</servlet-name>
		<servlet-class>com.vin.servlet.HelloWorldServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>HW</servlet-name>
		<url-pattern>/abc</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>TestLifeCycleServlet</servlet-name>
		<servlet-class>com.vin.servlet.TestLifeCycleServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>TestLifeCycleServlet</servlet-name>
		<url-pattern>/def</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>ThreeParams</servlet-name>
		<servlet-class>com.vin.servlet.ThreeParams</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>ThreeParams</servlet-name>
		<url-pattern>/servlet/ThreeParams</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>ShowParameters</servlet-name>
		<servlet-class>com.vin.servlet.ShowParameters</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>ShowParameters</servlet-name>
		<url-pattern>/servlet/ShowParameters</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>SetCookies</servlet-name>
		<servlet-class>com.vin.cookie.SetCookies</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>SetCookies</servlet-name>
		<url-pattern>/servlet/SetCookies</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>ShowCookies</servlet-name>
		<servlet-class>com.vin.cookie.ShowCookies</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>ShowCookies</servlet-name>
		<url-pattern>/servlet/ShowCookies</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>SessionInfoServlet</servlet-name>
		<servlet-class>com.vin.session.SessionInfoServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>SessionInfoServlet</servlet-name>
		<url-pattern>/servlet/SessionInfoServlet</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>ShowSession</servlet-name>
		<servlet-class>com.vin.session.ShowSession</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>ShowSession</servlet-name>
		<url-pattern>/servlet/ShowSession</url-pattern>
	</servlet-mapping>
</web-app>

未经允许不得转载:冰点网络 » Servlet学习(六)Session

分享到:更多 ()

评论 抢沙发

评论前必须登录!