Servlet之对多用户登录时HttpSession会话信息覆盖问题的担忧


    对这个问题存有疑惑,完全是因为不知道JSESIONID这个字段的值是如何产生的。然后在网上看到了这样一篇博客:《sessionid如何产生?由谁产生?保存在哪里?》,然后大致有了如下的粗浅理解。
    首先,鉴于JESSIONID的作用机制和编码方式,无须担心多用户登录时,服务器端的HttpSession保存的会话信息会被覆盖,因为每一个HttpSession对象都是通过客户端发送的JESSIONID来识别的,但是每一个JESSIONID又是唯一的,这种彼此之间一对一的关系,使得无须担心这个问题。

    PS:这里说的是在多个客户端级别上的多用户登录,而非同一个浏览器级别上的多用户登录!!!

1-JSESSIONID的作用机制

    JSEESIONID是在浏览器客户端第一次访问服务器端JavaEE程序时,随着HttpSession接口对象被Web容器所创建。通常,我们想要获取这个与某个客户端到服务端之间的连接通道绑定在一起的HttpSession对象,只需要调用HttpServletRequest参数对象的getSession()方法即可。
    对于javax.servlet.http包下的HttpSession接口对象,是与某次HTTP请求关联到一起的,随后就成为了某个Client-XXX与部署在Web容器中的Server-XXX之间会化状态维持的唯一标识。也即:

每次客户端Client-XXX与服务器端Server-XXX通信时,服务器端JavaEE程序都会通过JESSIONID字段来判断:
	当前客户端Client-xxx是否拥有访问某个页面/资源的权限,或者说是根据特定的JESSIONID来唯一标识
	某个客户端程序,
	
从而保证:在多个用户访问同一个服务器端程序时,存储在服务器端HttpSession对象中的信息不会被覆盖。

    Servlet-API文档中对HttpServletRequest参数对象的getSession()方法做了如下说明:

public HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
	返回一个与此次请求(request)相关联的会话对象,但是如果该会话对象不存在,就创建一个。
Returns:
the HttpSession associated with this request
See Also:
getSession(boolean)

2-JSESSIONID的是如何进行编码的?

    JESSIONID的唯一性是通过“随机数+时间+jvmid”来保证的,因为一个JESSIONID正是由这个几个部分组成的:

session在访问tomcat服务器HttpServletRequest的getSession(true)的时候创建,

tomcat的ManagerBase类提供创建sessionid的方法:随机数+时间+jvmid;
【此处:omcat的session的id值生成的机制是一个随机数加时间加上jvm的id值,jvm的id值会根据服务器的
	   硬件信息计算得来,因此不同jvm的id值都是唯一的】

JESSIONID通常是存储在服务器的内存中,tomcat的StandardManager类将session存储在内存中,
也可以持久化到file,数据库,memcache,redis等。客户端只保存sessionid到cookie中,
而不会保存session,session销毁只能通过invalidate或超时,关掉浏览器并不会关闭session。

3-代码验证

    先说一下验证思路:
(1)由于是多端的多用户登录,因此,使用了PC端和Pad端使用不同的账户进行登录,并将登录信息存储到HttpSession对象中,同时设置页面访问权限的控制,即:必须在客户端登陆成功的前提下,才可访问其他页面;
(2)在使用两个客户端交替地第二次访问其他页面时,打印其账户登录信息和JESSIONID的值,只要JESSIONID值不同、账户不同的PC端和Pad端的页面可以正常访问其它页面,那么就验证成功,否则验证失败。

提供前端页面

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
    <form action="loginservlet" method="post">
        <label for="uname">账户:</label><input type="text" placeholder="请输入账户" id="uname" name="username"/>
        <label for="uname">密码:</label><input type="password" placeholder="请输入密码" id="pswd" name="password"/>
        <input type="submit" name="登录" value="登录"/>
    </form>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
    <p>welcome to index.html!</p>
    <a href="loginoutservlet">退出登录</a>
</body>
</html>

后端代码

LoginServlet

package com.xwd.main.servlet;

import com.xwd.main.pojo.User;

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;
import java.io.IOException;

/**
 * @ClassName Login
 * @Description: com.xwd.main.servlet
 * @Auther: xiwd
 * @Date: 2022/2/6 - 02 - 06 - 18:27
 * @version: 1.0
 */
@WebServlet(
        name = "loginservlet",
        value = {
                "/loginservlet"
        }
)
public class LoginServlet extends HttpServlet {
    //methods
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        //设置参数解析编码格式
        req.setCharacterEncoding("UTF-8");
        //获取HttpSession
        HttpSession session = req.getSession();
        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //判断是否为空
        if (username!=null&&password!=null){
            if (("root".equals(username)&&"root".equals(password))||
                    ("root1".equals(username)&&"root1".equals(password))){
                //登陆成功
                //设置session
                User user=new User(username,password);
                session.setAttribute("user",user);
                System.out.println("登录-"+user.toString());
                //跳转到index.html(WEB-INF下的资源)
                req.getRequestDispatcher("WEB-INF/pages/index.html").forward(req,resp);
            }else {
                //登陆失败
                resp.sendRedirect(req.getContextPath()+"/login.html");
            }
        }else {
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }
    }
}

IndexServlet

package com.xwd.main.servlet;

import com.xwd.main.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @ClassName IndexServlet
 * @Description: com.xwd.main.servlet
 * @Auther: xiwd
 * @Date: 2022/2/6 - 02 - 06 - 18:48
 * @version: 1.0
 */
@WebServlet(
        name = "indexservlet",
        value = {
                "/indexservlet"
        }
)
public class IndexServlet extends HttpServlet {
    //methods

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        //设置request解析参数的编码格式
        req.setCharacterEncoding("UTF-8");
        //获取Session
        HttpSession session = req.getSession();
        //获取用户信息
        User user = (User)session.getAttribute("user");
        //判断用户是否为空
        if (user!=null){
            //获取用户名
            String usernmae = user.getUsernmae();
            if (null!=usernmae){
                //跳转到index.html
                req.getRequestDispatcher("WEB-INF/pages/index.html").forward(req,resp);
                //获取Cookie信息
                Cookie[] cookies = req.getCookies();
                for (Cookie cookie : cookies) {
                    if ("JSESSIONID".equals(cookie.getName())) {
                        System.out.println("JSESSIONID="+cookie.getValue());
                    }
                }
            }
        }else {
            //用户信息为空,跳转到登录页面
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }
    }
}

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <welcome-file-list>
        <welcome-file>login.html</welcome-file>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

</web-app>

测试结果

在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是席木木啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值