Servlet HttpSession 类向您展示了一种在多个页面请求或访问网站时识别用户并存储有关该用户的信息的方法。
servlet 容器使用此接口在 HTTP 客户端和 HTTP 服务器之间创建会话。
会话持续指定的时间段,跨越来自用户的多个连接或页面请求。一个会话通常对应一个用户,该用户可能会多次访问一个站点。
使用 HttpSession 在 java 类中创建会话
HttpSession session=request.getSession();
或通过在 getSession() 函数中添加 true 或 false
HttpSession session=request.getSession(true);
true – 返回现有会话对象,如果没有可用会话,它将创建新会话
false – 返回现有会话,如果没有可用会话,则返回 null
HttpSession 设置属性
使用指定的名称将对象绑定到此会话。您可以使用创建的会话对象为会话设置属性,如下所示
session.setAttribute("auth","candidjava");
Name 应该是 String 并且 Value 可以是任何对象;
HttpSession 获取属性
返回在此会话中与指定名称绑定的对象,如果在该名称下没有绑定任何对象,则返回 null。您可以从创建的会话中获取属性
String val=(String)session.getAttribute("auth");
HttpSession 无效
使此会话无效,然后解除绑定到它的任何对象。
session.invalidate();
Servlet HttpSession 示例
索引页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Simple HttpSession example</h1>
<form action="LoginController" method="post">
Username: <input type="text" name="uname"> <br>
Password: <input type="password" name="pass"> <br>
<input type="submit" value="Login">
</form>
</body>
</html>
登录控制器
签出以下用于创建 HttpSession 的 servlet 文件
package com.candidjava;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginController
*/
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String un=request.getParameter("uname");
String pw=request.getParameter("pass");
HttpSession session= request.getSession();
session.setAttribute("name", un);
response.sendRedirect("home.jsp");
}
}
成功页面
找到以下代码以在浏览器中显示 httpSession 值
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Retrieving HttpSession value</h1>
<br>
<%
String name=(String)session.getAttribute("name");
%>
HttpSession value is <%=name %>
</body>
</html>
输出截图:
截图 1
截图 2
下载源代码