前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Servlet总结三(HttpSession会话管理)

Servlet总结三(HttpSession会话管理)

作者头像
爱撒谎的男孩
发布2019-12-31 14:31:01
7230
发布2019-12-31 14:31:01
举报
文章被收录于专栏:码猿技术专栏码猿技术专栏

文章目录

  1. 1. Servlet总结三(HttpSession会话管理)
    1. 1.1. 简介
    2. 1.2. 常用方法
    3. 1.3. 使用
    4. 1.4. 简单的例子

Servlet总结三(HttpSession会话管理)

简介

HttpSession是提供一种方式,跨多个页面请求或对 Web 站点的多次访问标识用户并存储有关该用户的信息。 简单的来说就是能够实现全局的共享数据,可以跨多个页面请求,当然在Servlet中可以在同一个项目中的不同的Servlet中共享数据

常用方法

  • void setAttribute(String name, Object value) 绑定对象到此会话上
  • public void removeAttribute(String name) 移除绑定的对象
  • Object getAttribute(String name) 根据指定的属性名称获取指定的值(需要强转)
  • Enumeration getAttributeNames() 返回一个所有属性的枚举对象,可以通过Enumeration得到其中的值
  • public int getMaxInactiveInterval() 返回 servlet 容器在客户端访问之间将使此会话保持打开状态的最大时间间隔,以秒为单位(根据测试,这个默认的值为1800秒,如果在这个默认的时间之内没有响应,那么会话将会中断)
  • public void setMaxInactiveInterval(int interval) 指定在 servlet 容器使此会话失效之前客户端请求之间的时间间隔,以秒为单位。负数时间指示会话永远不会超时。

使用

我们可以通过HttpServletRequest的方法getSession() 获取对象,下面我们来使用其中的函数

代码语言:javascript
复制
    //Demo1中的doGet方法
    public void doGet(HttpServletRequest request,HttpServletResponse response){
        request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
        //获取对象
		HttpSession session=request.getSession();
		//设置属性login的值为auto
		session.setAttribute("login", "auto");                                                                   
        }

    //Demo2中的doGet方法
    public void doGet(HttpServletRequest request,HttpServletResponse response){
        //获取对象
		HttpSession session=request.getSession();
        //获取其中的login的值
        String login=session.getAttribute("login");
}

简单的例子

下面是一个简单的例子实现自动登录,在填入用户名和密码正确之后,并且勾选其中的自动登录选项,那么登录过一次后在一天之内,如果直接登录首页将会直接跳转到用户界面,实现自动登录的功能

  • index.jsp文件中实现的是简单的表单登录,并没有加上一些css,js,仅仅是一个例子
代码语言:javascript
复制
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
</head>

<body>
	<form action="Demo3" method="get">
		<label>username:</label><input type="text" name="username"></br> <label>password:</label><input
			type="password" name="password"></br>
			<label>自动登录:</label><input type="checkbox" name="login" value="auto">
			<input type="submit" value="提交">
	</form>
</body>
</html>

  • Demo3.java是用户的首页,实现检测自动登录,没有加一些页面在上面,但是其实是用户的首页
代码语言:javascript
复制
package com;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 Demo3 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		// 获取HttpSession对象
		HttpSession session = request.getSession();
		// 设置一天的访问时间间隔,如果超过这个时间,那么中断
		session.setMaxInactiveInterval(24 * 60 * 60);
		// 获取转发对象,页面跳转
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("HTML/user.html");
		// 获取表单的数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String login = request.getParameter("login");

		// 获取HttpSession中设置的属性名为login的值,如果为null,表示没有设置
		String value = (String) session.getAttribute("login");

		// 如果不为空,表示已经登录过一次了,并且允许自动登录,直接跳转到用户界面即可
		if (value != null) {
			// 直接跳转到用户界面
			dispatcher.forward(request, response);
		} else {
			// 如果用户名和密码正确
			if ("chenjiabing".equals(username) && "123456".equals(password)) {
				// 并且设置了自动登录
				if ("auto".equals(login)) {
					// 设置session的值
					session.setAttribute("login", "auto");
				}
				response.sendRedirect("HTML/user.html");
			}

		}

	}

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

}

说明: user.html是用户的主页,这里没有给出,可以自己设计

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-09-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Servlet总结三(HttpSession会话管理)
    • 简介
      • 常用方法
        • 使用
          • 简单的例子
          相关产品与服务
          容器服务
          腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档