现在的位置: 首页 > 综合 > 正文

10、关于Session

2018年02月05日 ⁄ 综合 ⁄ 共 8026字 ⁄ 字号 评论关闭

了解Session的概念
掌握HttpSession API
理解Session的生命周期
在JSP文件中控制Session
在JSP文件中设置Session范围内的共享数据

1、跟踪客户状态

- 建立包含有跟踪数据的隐藏字段
-重写包含额外参数的URL
-使用持续的Cookie
-使用ServletAPI中的Session(会话)机制

重点研究第四种

2、Session的概念:Session用于跟踪客户的状态。Session指的是在一段时间内,单个客户与web服务器的一连串相关的交互过程。在一个Session中,客户可能会多次请求访问同一个网页,也有可能请求访问各种不同的服务器资源。

3、Session的运行机制

-当一个Session开始时,Servlet容器将创建一个HttpSession对象,在HttpSession对象中可以存放客户状态的信息(例如购物车);
-Servlet容器为HttpSession分配一个唯一的标识符,称为Session ID。Servlet容器把SessionID作为Cookie保存在客户的浏览器中
-每次客户发出HTTP请求时,Servlet容器可以从HttpServletRequest对象中读取SessionID,然后根据SessionID找到相应的HttpSession对象,从而获取客户的状态信息

4、HttpSession 接口

    - getID()——返回Session的ID
    - invalidate()——是当前的Session失效,Servlet容器会释放HttpSession对象占用的资源
    - setAttribute(String name,Object object)
    - getAttribute(String name)
    - isNew()——判断是否是新创建的Session。如果是新创建的Session,返回true,否则返回false
    - setMaxInactiveInterval()——设定一个Session可以处于不活动状态的最大时间间隔,以秒为单位,如果超过这个时间,Session自动失效。如果设置为负数,表示不限制Session处于不活动状态的时间。

5、Session的生命周期

- 当客户第一次访问web应用中支持Session的某个网页时,就会开始一个新的Session
- 接下来当客户浏览这个web应用的不同网页时,始终处于同一个Session中
- 默认情况下,JSP网页都是支持Session的,也可以通过以下语句显式声明支持Session:<%@ page session="true" >

- 在以下情况中,Session将结束生命周期,Servlet容器会将Session所占用的资源释放掉:
    1)客户端关闭浏览器
    2)Session过期
    3)服务器端调用了HttpSession的invalidate()方法

- 严格的讲,做不到这一点。可以做一点努力的办法是在所有的客户端页面里使用javascript代码window.onclose来监视浏览器的关闭动作,然后向服务器发送请求来删除session。
- 但是对于浏览器崩溃或者强行杀死进程这些非常规手段仍然无能为力。
- 实际上在项目中我们也不会这么做,而是让服务器在Session过期时将其删除。

有两种cookie,一种是可以保存在硬盘上的,一种是存在于浏览器进程上的,而session对应的cookie是保存于浏览器进程上的,称为会话cookie,当关闭浏览器窗口时,浏览器进程上的cookie消失,而服务器端的会话session还存在。

- Session的过期,是指当Session开始后,在一段时间内客户没有和web服务器交互,这个Session会失效,HttpSession的setMaxInactiveInterval()方法可以设置允许Session保持不活动状态的时间(以秒为单位),如果超过这一时间,Session就会失效。

 6、一个使用session的例子,登录后根据用户不同,访问不同的页面:

登录页面login.jsp:

<%@ 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 'login.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>
	<%--
	这一段针对请求转发	
	<% String authority = (String) request.getAttribute("authority"); %>  
  
    <form action="UserLoginServlet" method="post">
    username:<input type="text" name="username" value="<%= null == request.getAttribute("username")? "" : request.getAttribute("username")  %>" ><br>
    password:<input type="password" name="password"/><br/>
    authority:<select name="authority">
    			<option value="1" <%= "1".equals(authority)? "selected" : "" %>> common user</option>
    			<option value="2" <%= "2".equals(authority)? "selected" : "" %> >administrator</option>
    </select>
    <br/>
    <input type="submit" value="submit" >
        </form>
	 --%>
	
	 
  <% String username = request.getParameter("username");
  	 String authority = request.getParameter("authority");
  %>
    <form action="UserLoginServlet" method="post">
    username:<input type="text" name="username" value='<%= null == username ? "" : username %>' ><br>
    password:<input type="password" name="password"/><br/>
    authority:<select name="authority">
    			<option value="1" <%= "1".equals(authority) ?  "selected" : "" %> > common user</option>
    			<option value="2" <%= "2".equals(authority) ?  "selected" : "" %> >administrator</option>
    </select>
    <br/>
    <input type="submit" value="submit" >
        </form>
  </body>
</html>

处理登录请求的Servlet:UserLoginServlet

import java.io.IOException;

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

import com.cdtax.bean.User;

public class UserLoginServlet extends HttpServlet
{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		User user = new User();
		HttpSession session = req.getSession();
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String authority = req.getParameter("authority");
		
		if("1".equals(authority))
		{
			if("zhangsan".equals(username) && "123".equals(password))
			{
				
				
				user.setUsername(username);
				user.setPassword(password);
				user.setAuthority(authority);
				
				
				session.setAttribute("user", user);
				
				req.getRequestDispatcher("session/index.jsp").forward(req, resp);
			}
			else
			{
				resp.sendRedirect("session/login.jsp?username=" + username + "&authority=" + authority);
//以下是使用请求转发的方式				
//				req.setAttribute("username", username);
//				req.setAttribute("authority", authority);
//				RequestDispatcher rd =req.getRequestDispatcher("session/login.jsp");
//				rd.forward(req, resp);
			}
		}
		
		else if("2".equals(authority))
		{
			if("lisi".equals(username) && "456".equals(password))
			{
				user.setUsername(username);
				user.setPassword(password);
				user.setAuthority(authority);
				
				
				session.setAttribute("user", user);
				req.getRequestDispatcher("session/index.jsp").forward(req, resp);
			}
			else
			{
				resp.sendRedirect("session/login.jsp?username=" + username + "&authority=" + authority);
//以下是使用请求转发的方式
//				req.setAttribute("username", username);
//				req.setAttribute("authority", authority);
//				RequestDispatcher rd =req.getRequestDispatcher("session/login.jsp");
//				rd.forward(req, resp);
			}
		}
		
		else
		{
			resp.sendRedirect("session/login.jsp?username=" + username + "&authority=" + authority);
//以下是使用请求转发的方式
//			RequestDispatcher rd =req.getRequestDispatcher("session/login.jsp");
//			rd.forward(req, resp);
		}
	}
}

包装用户信息的JavaBean:User

public class User
{
	private String username;
	
	private String password;
	
	private String authority;
	
	public String getUsername()
	{
		return username;
	}
	
	public void setUsername(String username)
	{
		this.username = username;
	}
	
	public String getPassword()
	{
		return password;
	}
	
	public void setPassword(String password)
	{
		this.password = password;
	}
	
	public String getAuthority()
	{
		return authority;
	}
	
	public void setAuthority(String authority)
	{
		this.authority = authority;
	}
	
	
}

登录成功后的页面:index.jsp,根据用户不同权限,显示不同的链接

<%@ page language="java" import="java.util.*,com.cdtax.bean.User" 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>
  	<% User user = (User)session.getAttribute("user");
  		if(null == user)
  		{
  			response.sendRedirect("session/login.jsp");
  			return;
  		}
  	%>
    <a href="QueryServlet">Query</a><br>
    <% if(((User)session.getAttribute("user")).getAuthority().equals("2")) { %>
    <a href="UpdateServlet">Update</a>
    <% } %>
  </body>
</html>

处理不同用户业务的Servlet:QueryServlet和UpdateServlet

import java.io.IOException;

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

public class QueryServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		 HttpSession session = req.getSession();
		 
		 if(null == session.getAttribute("user"))
		 {
			 resp.sendRedirect("session/login.jsp");
			 return;
		 }
		 
		 System.out.println("成功");
	}
}


import java.io.IOException;

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

import com.cdtax.bean.User;

public class UpdateServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		HttpSession session = req.getSession();
		 
		 if(null == session.getAttribute("user"))
		 {
			 resp.sendRedirect("session/login.jsp");
			 return;
		 }
		 
		 User user = (User)session.getAttribute("user");
		 if("1".equals(user.getAuthority()))
		 {
			 System.out.println("失败");
		 }
		 else
		 {
			 System.out.println("成功");
		 }
	}
}

 

 

【上篇】
【下篇】

抱歉!评论已关闭.