使用servlet显示session ID信息

实操
1.参考P147的案例,编写Servlet程序,查看当前浏览器Cookie中保存有哪些信息?
2.定义两个Servlet程序,都向页面显示当前的session ID,
(1)打开浏览器,输入程序一映射的地址,观察session ID的值,在同一窗口的地址栏再输入程序二映射的地址,观察session ID是否相同?
(2)打开浏览器输入程序一映射的地址,观察session ID的值,关闭浏览器后重新打开,输入程序二映射的地址,观察session ID是否相同?
(3)再尝试其它的情况,记录观察到的session ID有什么规律?(不同的浏览器、同一浏览器不同的窗口、……)

LastAccessServlet类:

package ch04;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LastAccessServlet	extends HttpServlet{
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html;charset=UTF-8");
		Cookie[] cookies = request.getCookies();			//cookies对象
		PrintWriter out = response.getWriter();				
		HttpSession session = request.getSession();			//session对象
		out.println("Session ID:"+ session.getId()+"</br>");		//调用session接口显示session id
		String usersdata[] = {"usrename","major","Telephone"};			//构建cookie内容,users是键,value是值
		String valuedata[] = {"gongping","Computer_Science","123456789"};
		for(int i = 0;i<usersdata.length;i++) {
			Cookie data = new Cookie(usersdata[i],valuedata[i]);		//读取cookie内容到对象data中发送给客户端
			response.addCookie(data);									//发送data对象为cookie
		}
		for(int i = 0;cookies != null && i<cookies.length;i++) {		//将cookie对象中的值分别输出显示
				out.print(cookies[i].getName()+":"+cookies[i].getValue()+"</br>");			
		}

	}
	public void doPost(HttpServletRequest request,HttpServletResponse response)
	throws ServletException,IOException{
		doGet(request,response);
	}
}

LastAccessServlet1类:

package ch04;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LastAccessServlet1	extends HttpServlet{
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html;charset=UTF-8");
		Cookie[] cookies = request.getCookies();
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		out.println("Session ID:"+ session.getId()+"</br>");

		
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response)
	throws ServletException,IOException{
		doGet(request,response);
	}
}

默认session值:

(1)同一窗口下,不同映射

(2)关闭浏览器

(3)不同浏览器

posted @ 2021-04-22 17:36  网抑云黑胶SVIP用户  阅读(297)  评论(0编辑  收藏  举报