Session的创建和设置
1、Session的获取
(1)无参的方法:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession httpSession=request.getSession();
System.out.println(httpSession.getId());
}

请求中无Cookie,但是响应中存在Cookie:


当再次访问该Servlet的时候,请求中存在Cookie,响应中的Cookie已经没有了:


以上为无参的方法获取Session,如果没有Session则创建一个,如果有则直接返回。
(2)有参的方法:
参数为false:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession httpSession=request.getSession(false);
System.out.println(httpSession.getId());
}
如果有Session则直接返回。
没有的话返回500错误:

参数为true:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession httpSession=request.getSession(true);
System.out.println(httpSession.getId());
}
此方法与不加参数等效。
2、Session的有效期限:

前三次访问是连续访问三次CookieServlet,可以看出,SESSIONID的值是不会发生变化的,但是当关闭了浏览器,第四次访问CookieServlet时,SESSIONID发生了变化;第五次为更换了浏览器之后的结果,SESSIOID依旧会发生变化。
以下情况下Session需要重新建立:
(1)用户关闭了浏览器。但是关闭了浏览器并不代表Seesion已经被销毁了,因为Session保存在服务器内部。
(2)关闭了服务器。
(3)用户没有向服务器提出请求(超过30分钟),过期后服务器自动删除,从不操作服务端资源开始计时。

可以修改(直接修改或在自己的web.xml中配置,将默认的时间覆盖掉)。
3、Session的设置:
(1)时间:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession httpSession=request.getSession(true);
httpSession.setMaxInactiveInterval();//十秒后失效
System.out.println(httpSession.getId());
}
第一次访问,成功返回SESSIONID。

过十几秒钟后重新访问发现SESSIONID的值已经改变了:

这是因为第一个SESSIOID已经过期了,需要创建第二个。
(2)强制失效(手动销毁):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession httpSession=request.getSession(true);
httpSession.invalidate();
System.out.println(httpSession.getId());
}

即执行invalidate()后可以将创建的SESSION立即结束。
4、session的特点:
(1)存储在服务器端。
(2)依赖于Cookie,借助Cookie存储JSESSIONID。
(3)存在有效期限。
5、session的数据共享
要体现出Session的数据共享,需要建立两个Servlet:
第一个:建立Session,将值设置为Tom。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String name="Tom";
HttpSession httpSession=request.getSession(true);
httpSession.setAttribute("name",name);
System.out.println(httpSession.getId());
}
第二个获取Session:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession httpSession=request.getSession();
System.out.println(httpSession.getAttribute("name"));
}

也就是说对于不同的请求,都可以共享Session中的数据,他们的请求针对的是同一个Session,但是要保证Session没有失效。即没有关闭浏览器,没有过期,Session中的数据存储在服务器。
6、session的应用
(1)使用Cookie实现的登录的不足:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");//设置浏览器编码格式
Cookie[] cookies=request.getCookies();
Connection con=null;
login log= null;
int successNum=0;
try {
con= C3p0Utils.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "Select * from login";
List<login> list = qr.query(con, sql, new BeanListHandler<login>((login.class)));
if(cookies!=null) {//验证数据库中是否有与Cookie对应的用户
for (int i = 0; i < list.size(); i++) {
log= list.get(i);
for (Cookie cookie : cookies) {
if((log.getAccount().equals(cookie.getName()))&&(log.getPassword().equals(cookie.getValue()))){
successNum++;
}
}
}
if(successNum>=1){
response.getWriter().write("Successful login with Cookie!");
}
else{
request.getRequestDispatcher("page").forward(request,response);
}
}
else{
request.getRequestDispatcher("page").forward(request,response);//请求转发
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");//设置浏览器编码格式
response.getWriter().write("<html>");
response.getWriter().write("<head>");
response.getWriter().write("<title>");
response.getWriter().write("Login");
response.getWriter().write("</title>");
response.getWriter().write("</head>");
response.getWriter().write("<body bgcolor=\"aqua\">");
response.getWriter().write("<center>");
response.getWriter().write("<h3>");
response.getWriter().write("欢迎你"+request.getParameter("account"));
response.getWriter().write("</h3>");
response.getWriter().write("</center>");
response.getWriter().write("</body>");
}
使用Cookie虽然实现了三天免登录的基础功能,但是,如果在用Cookie登录成功后需要重定向(两次请求,request对象不能携带数据)到另外一个Cookie时,request获取的值在重定向的Servlet中已经不再起作用了,访问的结果只能是空值。
(2)使用Session的请求共享功能,实现在不同的Servlet跳转过程中依旧能够通过request获得用户信息。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");//设置浏览器编码格式
Cookie[] cookies=request.getCookies();
Connection con=null;
login log= null;
int successNum=0;
try {
con= C3p0Utils.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "Select * from login";
List<login> list = qr.query(con, sql, new BeanListHandler<login>((login.class)));
if(cookies!=null) {//验证数据库中是否有与Cookie对应的用户
for (int i = 0; i < list.size(); i++) {
log= list.get(i);
for (Cookie cookie : cookies) {
if((log.getAccount().equals(cookie.getName()))&&(log.getPassword().equals(cookie.getValue()))){
HttpSession httpSession=request.getSession();
httpSession.setAttribute("login",log);
successNum++;
}
}
}
if(successNum>=1){
response.sendRedirect("/Servlet_login_war_exploded/main");//重定向
}
else{
request.getRequestDispatcher("page").forward(request,response);
}
}
else{
request.getRequestDispatcher("page").forward(request,response);//请求转发
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
在通过Cookie登录成功后,创建了Session,对Session进行了赋值,而在重定向到MainServlet后,可以从Session中获取值。虽然在不同的Servlet中,是不同的请求,但是依旧能够通过Session获取值。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login log= (login) request.getSession().getAttribute("login");
response.setContentType("text/html; charset=utf-8");//设置浏览器编码格式
response.getWriter().write("<html>");
response.getWriter().write("<head>");
response.getWriter().write("<title>");
response.getWriter().write("Login");
response.getWriter().write("</title>");
response.getWriter().write("</head>");
response.getWriter().write("<body bgcolor=\"aqua\">");
response.getWriter().write("<center>");
response.getWriter().write("<h3>");
response.getWriter().write("欢迎你"+log.getAccount());
response.getWriter().write("</h3>");
response.getWriter().write("</center>");
response.getWriter().write("</body>");
}

Session的创建和设置的更多相关文章
- 什么叫session和cookie-及其设置
http的无状态? 保持状态, 是指当程序关闭后重启, 上一次操作的历史还能继续, 保持的. 如word中的 "选项"设置. 如windows系统的设置等等. http的设计目的, ...
- 使用HttpSessionListener接口监听Session的创建和失效
转自:http://uule.iteye.com/blog/824115 HttpSessionListener : Session创建事件发生在每次一个新的session创建的时候,类似地Sessi ...
- 关于web会话中的session过期时间的设置
关于web会话中的session过期时间的设置 1.操作系统: 步骤:开始——〉管理工具——〉Internet信息服务(IIS)管理器——〉网站——〉默认网站——〉右键“属性”——〉主目录——〉配置— ...
- Session管理之超时设置和强制下线
关于Session,在Java Web开发中,为我们提供了很多方便,Session是由浏览器和服务器之间维护的.好吧,闲话不多说,下面让我们一步一步来实现它们. (一)首先来说下Session超时时间 ...
- [原创]java WEB学习笔记31:会话与状态管理 session机制 概述(定义,session机制,session的声明周期,保存session的方式,Session的创建与删除)
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
- Session中短信验证码设置有效时间
Session中短信验证码设置有效时间 package com.mozq.boot.kuayu01.controller; import org.springframework.web.bind.an ...
- 如何通过命令行创建和设置一个MySQL用户
我想要在MySQL服务器上创建一个新的用户帐号,并且赋予他适当的权限和资源限制.如何通过命令行的方式来创建并且设置一个MySQL用户呢? 要访问一个MySQL服务器,你需要使用一个用户帐号登录其中方可 ...
- iOS之UI--指示器HUD的创建和设置
指示器的创建和设置 渐变动画 描述: 使用label就能制作指示器,原理:就是让label以动画的形式慢慢显示和消失 最好是半透明的 指示器有时候也被称为:HUD,遮盖,蒙版 思路步骤: 1.先在st ...
- yii创建与设置默认控制器并载入模板
yii创建与设置默认控制器并载入模板 一.创建控制器 在protected下的controllers文件夹中创建自定义的控制器文件,比如: IndexController.php (文件名首字母大写) ...
随机推荐
- (三十五)c#Winform自定义控件-Tab页
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- monkey学习总结笔记
一.什么是monkey? Monkey是Android中的一个命令行工具,可以运行在模拟器里或实际设备中.它向系统发送伪随机的用户事件流(如按键输入.触摸屏输入.手势输入等),实现对正在开发的应用程序 ...
- [HNOI2008]玩具装箱toy(斜率优化dp)
前言 这是我写的第一道$dp$斜率优化的题目,$dp$一直都很菜,而且咖啡鸡都说了这是基础的东西,然而看别人对$dp$斜率优化一大堆公式又看不懂就老老实实做几道题目,这个比较实在 描述 给出$n$和$ ...
- ZooKeeper实现读写锁
在上一篇文章,我们已经实现了分布式锁.今天更进一步,在分布式锁的基础之上,实现读写锁. 完整代码在 https://github.com/SeemSilly/codestory/tree/master ...
- spring中的事件 applicationevent 讲的确实不错(转)
event,listener是observer模式一种体现,在spring 3.0.5中,已经可以使用annotation实现event和eventListner里. 我们以spring-webflo ...
- 一键部署 Spring Boot 到远程 Docker 容器,就是这么秀!
不知道各位小伙伴在生产环境都是怎么部署 Spring Boot 的,打成 jar 直接一键运行?打成 war 扔到 Tomcat 容器中运行?不过据松哥了解,容器化部署应该是目前的主流方案. 不同于传 ...
- Python 基础1 - 位运算符
引言 本文主要介绍位运算符,实际上Python有以下7类运算符: [赋值运算符].[比较运算符].[算术运算符].[逻辑运算符].[身份运算符].[成员运算符].[位运算符] 位运算符 按位运算符是把 ...
- Spring框架之JdbcTemplate
Spring框架之JdbcTemplate 一.JdbcTemplate简介 Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到Jd ...
- Keras(五)LSTM 长短期记忆模型 原理及实例
LSTM 是 long-short term memory 的简称, 中文叫做 长短期记忆. 是当下最流行的 RNN 形式之一 RNN 的弊端 RNN没有长久的记忆,比如一个句子太长时开头部分可能会忘 ...
- [python]标准比较运算符
1. python的标准比较运算符,根据表达式的值的真假返回布尔值. 比较运算符: < <= > >= == != <> >>& ...