Servlet session
一、session介绍
Session用于保存服务端与客户端“会话”的信息。例如你逛淘宝时添加到购物车中的商品的信息就是保存到Session中。与Cookies不同的是,Session保存在服务端。每个客户端会有一个与之关联的Session,服务器会将Session的ID写到客户端的Cookies或者URL。如果客户端禁止Cookies了,服务器会将ID写到URL中。
二、Session实例
public class ShowSession extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
//得到客户端对应的session对象,true表示如果在服务器端找不到对应的session对象则创建一个
//得到的是一个session引用,实现HttpSession的具体类
HttpSession session = request.getSession(true);
String heading;
// Use getAttribute instead of getValue in version 2.2.
//得到Session内,与accessCount名字所对应的值Integer accessCount = (Integer) session.getAttribute("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
// Use setAttribute instead of putValue in version 2.2.
//像Session内放入对象,第一个参数作为key或者称之为名字,与Map差不多
session.setAttribute("accessCount", accessCount);out.println("<html><head><title>Session追踪</title></head>"
+ "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">"
+ heading + "</H1>\n"
+ "<H2>Information on Your Session:</H2>\n"
+ "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
+ "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n"
+ "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n"
+ "<TR>\n" + " <TD>Creation Time\n" + " <TD>"
//表示Session对象的创建时间
+ new Date(session.getCreationTime()) + "\n" + "<TR>\n"
+ " <TD>Time of Last Access\n" + " <TD>"
//最后一次访问时间
+ new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n"
+ " <TD>Number of Previous Accesses\n" + " <TD>"
+ accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>");
}
三、第二个Seesion实例
public class SessionInfoServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException{
HttpSession mySession = request.getSession(true);
response.setContentType("text/html");
//response表示服务端的回应
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Session Info Servlet</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<H3>Session Information</H3>");
//判断Session是否创建
out.println("New Session: " + mySession.isNew());
//得到Session的ID
out.println("<BR>Session ID: " + mySession.getId());
out.println("<BR>Session Creation Time: " +
new java.util.Date(mySession.getCreationTime()));
out.println("<BR>Session Last Accessed Time: " +
new java.util.Date(mySession.getLastAccessedTime()));
out.println("<H3>Request Information</H3>");
out.println("Session ID from Request: " +
//request代表客户端的请求,获得从客户端带来的ID
request.getRequestedSessionId());
out.println("<BR>Session ID via Cookie: " +
//判断ID号是否从Cookie内取出来的
request.isRequestedSessionIdFromCookie());
out.println("<BR>Session ID via rewritten URL: " +
//判断ID号是否从URL内取出来的
request.isRequestedSessionIdFromURL());
out.println("<BR>Valid Session ID: " +
//判断从客户端取出的ID是否合法
request.isRequestedSessionIdValid());
out.println("</BODY></HTML>");
out.close(); //close output stream
}
四、Session URL重写
public class URLSession extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
out.println("<html><head><title>Session追踪</title></head>"
+ "<BODY>\n"
+ "session id:" + session.getId() + "</br>"
+ "from url:" + request.isRequestedSessionIdFromURL() + "</br>"
+ "from cookie:" + request.isRequestedSessionIdFromCookie() + "</br>"
//URL重写
+ "<a href=" + response.encodeURL(request.getRequestURL().toString())
+ ">test</a> </br>"
//得到当前访问的Session地址
+ "<a href=" + request.getRequestURI().toString() + ">test</a>"
+ "</BODY></HTML>"); }
五、Session总结
Session是服务器端的一块内存
Session与客户端窗口对应,只要客户端窗口不关就可以访问到,默认失效时间30m,在Tomacat的conf文件夹下的web.xml文件中配置。
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
客户端与服务器有对应的SessionID
客户端向服务器端发送SessionID的时候有两种方式:
1、Cookie
2、重写URL
Servlet session的更多相关文章
- JavaWeb学习记录总结(二十九)--Servlet\Session\Cookie\Filter实现自动登录和记住密码
一.Servlet package autologin.servlet.login; import java.io.IOException;import java.security.MessageDi ...
- jsp&servlet——session监听
session监听,需要实现HttpSessionAttributeListener接口 attributeAdded:监听添加session attributeRemoved:监听删除session ...
- Servlet Session 跟踪
HTTP 是一种"无状态"协议,这意味着每次客户端检索网页时,客户端打开一个单独的连接到 Web 服务器,服务器会自动不保留之前客户端请求的任何记录. 但是仍然有以下三种方式来维持 ...
- Servlet session的理解
servlet参见http://blog.csdn.net/bryanliu1982/article/details/5214899 session参见http://lavasoft.blog.51c ...
- Servlet Session MVC模式
一 什么是Session 当首次使用session时,服务器端要创建session,session是保存在服务器端,而给客户端的session的id(一个cookie中保存了sessionId). ...
- Servlet Session的使用
Session 是服务器端会话技术.当浏览器访问 Web 服务器的资源时,服务器可以为每个用户浏览器创建一个 Session 对象,每个浏览器独占一个 Session 对象.由于每个浏览器独占一个 S ...
- servlet session 相关
1.session是server维护的一个变量,如果消除每个session?----这里只做指定key的session删除 1.1.显示调用 废除指定key的session session.remov ...
- 在报表中给session赋值实现报表间参数共享
1. 问题描述 在报表开发工具FineReport中,若有几张不同的报表,每张报表都有一个共同的项可以选择,比如日期时间.我们希望选择了第一张报表的时间之后,其他报表的默认时间都变为第一张报表选择的时 ...
- Using Sessions and Session Persistence---reference
Using Sessions and Session Persistence The following sections describe how to set up and use session ...
随机推荐
- Unix哲学
01. 模块原则:使用简洁的接口拼合简单的部件. 02. 清晰原则:清晰胜于机巧. 03. 组合原则:设计时考虑拼接组合. 04. 分离原则:策略同机制分离,接口同引擎分离. 05. 简洁原则:设计要 ...
- 基于Simple Image Statistics(简单图像统计,SIS)的图像二值化算法。
这是个简单的算法,是全局二值算法的一种,算法执行速度快. 算法过程简单描述如下: 对于每一个像素,做如下处理 1.计算当前像素水平和垂直方向的梯度. (two gradients are calcul ...
- Hibernate考试选择题解析
1.在Hibernate中,以下关于主键生成器说法错误的是(AC). A.increment可以用于类型为long.short或byte的主键(byte类型不可以) B.identity用于如SQL ...
- jdbc java数据库连接 5)CallableStatement 接口
CallableStatement执行存储过程(也是预编译语言) 首先在sql中执行以下带有输入参数的代码: DELIMITER $ CREATE PROCEDURE pro_findById(IN ...
- thinkphp怎么实现图片验证码
1.控制器 function verify() { ob_clean();//丢弃输出缓冲区中的内容 $config = array( 'fontSize' => 20, // 字体大小 'le ...
- 深入理解JVM内幕(转)
转自:http://blog.csdn.net/zhoudaxia/article/details/26454421/ 每个Java开发者都知道Java字节码是执行在JRE((Java Runtime ...
- MongoDB之分片集群与复制集
分片集群 1.1.概念 分片集群是将数据存储在多台机器上的操作,主要由查询路由mongos.分片.配置服务器组成. ●查询路由根据配置服务器上的元数据将请求分发到相应的分片上,本身不存储集群的元数据, ...
- JSP基础学习
JQuery教程: http://www.w3school.com.cn/jquery/ HTTP协议的 http://www.w3.org/Protocols/rfc2616/rfc2616.htm ...
- .net线程池
线程池的作用线程池,顾名思义,线程对象池.Task和TPL都有用到线程池,所以了解线程池的内幕有助于你写出更好的程序.由于篇幅有限,在这里我只讲解以下核心概念: 线程池的大小 如何调用线程池添加任务 ...
- Word2Vec 使用总结
word2vec 是google 推出的做词嵌入(word embedding)的开源工具. 简单的说,它在给定的语料库上训练一个模型,然后会输出所有出现在语料库上的单词的向量表示,这个向量称为&qu ...