使用 Eclipse 的 Servlet HttpSession 示例

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

下载源代码

HttpSession 示例war

HttpSession 示例 zip

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值