如何使用 JSESSIONID 手动加载 Java 会话? [英] How can I manually load a Java session using a JSESSIONID?

查看:28
本文介绍了如何使用 JSESSIONID 手动加载 Java 会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理多部分表单发布的 servlet.该帖子实际上是由嵌入在页面中的 Flash 文件上传组件制作的.在某些浏览器中,Flash 生成的 POST 不包含 JSESSIONID,这使我无法在发布期间从会话中加载某些信息.

I have a servlet which handles a multipart form post. The post is actually being made by a Flash file upload component embedded in the page. In some browsers, the Flash-generated POST doesn't include the JSESSIONID which is making it impossible for me to load certain information from the session during the post.

Flash 上传组件在特殊表单字段中包含 cookie 和会话信息.使用此表单字段,我实际上可以检索 JSESSIONID 值.问题是,我不知道如何使用这个 JSESSIONID 值来手动加载该特定会话.

The flash upload component does include cookie and session information within a special form field. Using this form field, I can actually retrieve the JSESSIONID value. The problem is, I don't know how to use this JSESSIONID value to manually load that specific session.

编辑 - 基于 ChssPly76 的解决方案,我创建了以下 HttpSessionListener 实现:

Edit - Based on ChssPly76's solution, I created the following HttpSessionListener implementation:

    @Override
    public void sessionCreated(final HttpSessionEvent se) {
        final HttpSession session = se.getSession();
        final ServletContext context = session.getServletContext();
        context.setAttribute(session.getId(), session);
    }

    @Override
    public void sessionDestroyed(final HttpSessionEvent se) {
        final HttpSession session = se.getSession();
        final ServletContext context = session.getServletContext();
        context.removeAttribute(session.getId());
    }

将所有会话添加到 ServletContext 作为由其唯一 id 映射的属性.我可以在上下文中放置一个会话地图,但这似乎是多余的.请发表对此决定的任何想法.接下来,我将以下方法添加到我的 servlet 以通过 id 解析会话:

Which adds all sessions to the ServletContext as attributes mapped by their unique ids. I could put a Map of sessions in the context instead, but it seems redundant. Please post any thoughts on this decision. Next, I add the following method to my servlet to resolve the session by id:

    private HttpSession getSession(final String sessionId) {
        final ServletContext context = getServletContext();
        final HttpSession session = (HttpSession) context.getAttribute(sessionId);
        return session;
    }

推荐答案

没有通过 id 检索会话的 API.

There is no API to retrieve session by id.

然而,你可以做的是实现一个 会话侦听器 在您的 Web 应用程序中,并手动维护由 id 键控的会话映射(会话 id 可通过 session.getId()).然后,您将能够检索您想要的任何会话(而不是像其他人建议的那样欺骗容器用它替换您当前的会话)

What you can do, however, is implement a session listener in your web application and manually maintain a map of sessions keyed by id (session id is retrievable via session.getId()). You will then be able to retrieve any session you want (as opposed to tricking container into replacing your current session with it as others suggested)

这篇关于如何使用 JSESSIONID 手动加载 Java 会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆