Servlet总结三(HttpSession会话管理)

  • 2019 年 12 月 31 日
  • 筆記

文章目录

  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() 获取对象,下面我们来使用其中的函数

    //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,仅仅是一个例子
<%@ 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是用户的首页,实现检测自动登录,没有加一些页面在上面,但是其实是用户的首页
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是用户的主页,这里没有给出,可以自己设计