HttpSession

1. HttpSession概述

  • HttpSession是由JavaWeb提供的,用来会话跟踪的类。session是服务器端对象,保存在服务器端!!!
  • HttpSession是Servlet三大域对象之一(request、session、application(ServletContext)),所以它也有setAttribute()、getAttribute()、removeAttribute()方法
  • HttpSession底层依赖Cookie,或是URL重写!

2. HttpSession的作用

  • 会话范围:会话范围是某个用户从首次访问服务器开始,到该用户关闭浏览器结束!

会话:一个用户对服务器的多次连贯性请求!所谓连贯性请求,就是该用户多次请求中间没有关闭浏览器!

  • 服务器会为每个客户端创建一个session对象,session就好比客户在服务器端的账户,它们被服务器保存到一个Map中,这个Map被称之为session缓存!

Servlet中得到session对象:HttpSession session = request.getSession();
Jsp中得到session对象:session是jsp内置对象之下,不用创建就可以直接使用!

  • session域相关方法:

void setAttribute(String name, Object value);
Object getAttribute(String name);
void removeAttribute(String name);

3. 案例1:演示保存用户登录信息(精通)

  • 案例相关页面和Servlet:

login.jsp:登录页面
succ1.jsp:只有登录成功才能访问的页面
succ2.jsp:只有登录成功才能访问的页面
LoginServlet:校验用户是否登录成功!

  • 各页面和Servlet内容:

login.jsp:提供登录表单,提交表单请求LoginServlet
LoginServlet:获取请求参数,校验用户是否登录成功
<> 失败:保存错误信息到request域,转发到login.jsp(login.jsp显示request域中的错误信息)
<> 成功:保存用户信息到session域中,重定向到succ1.jsp页面,显示session域中的用户信息
succ1.jsp:从session域获取用户信息,如果不存在,显示“您还没有登录”。存在则显示用户信息
succ2.jsp:从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>
  <h1>登录</h1>
  <%
  String message="";
  String msg = (String)request.getAttribute("errormsg");
  if(msg != null){
	  message=msg;
  }
  %>
  <font color="red"><b><%=message %></b></font>
    <form action="/day11_2/LoginServlet" method="post">
    用户名<input type="text" name="user"/><br>
    密 码<input type="password" name="passsword"/><br>
    <input type="submit" value="确定">
    </form>
  </body>
</html>

succ1.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 'succ1.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 username=(String)session.getAttribute("user");
    if(username==null)
    {
    	request.setAttribute("errormsg","您还没有登录!");
    	request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
    	return;
    }
    %>
    
    欢迎用户<%=username %> !!!<br>
 
    
  </body>
</html>

succ2.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 'succ1.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 username=(String)session.getAttribute("user");
    if(username==null)
    {
    	request.setAttribute("errormsg","您还没有登录!");
    	request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
    	return;
    }
    %>
    欢迎用户<%=username %> !!!<br>
  </body>
</html>

LoginServlet.java

package day11_2;

import java.io.IOException;
import java.io.PrintWriter;

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 LoginServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //以下两行处理中文
		request.setCharacterEncoding("utf-8");
        response.setContentType("text/htm;charset=utf-8");
		String user=request.getParameter("user");
		String password=request.getParameter("password");
		if(!user.equalsIgnoreCase("itcast")){
			//用户名只要不是itcast都是正确的
			//成功:保存正确的信息到session中
			HttpSession session=request.getSession();
			session.setAttribute("user", user);
			session.setAttribute("password", password);
			//重定向的路径 相对于当前主机
			response.sendRedirect("/day11_2/session2/succ1.jsp");
		}else{
			//失败:
			//保存错误信息到request域并转发回login.jsp
			request.setAttribute("errormsg", "用户或密码错误");
			//转发路径:相对于当前项目。。
			//获得RequestDispatcher要记得调用forword():提醒页面调用server函数
			request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
		}
		
	}

}