【问题标题】:How can i achieve active(current) UserContext in some classes?如何在某些类中实现活动(当前)UserContext?
【发布时间】:2011-07-30 01:50:31
【问题描述】:

我有问题。我希望有人可以帮助我。

我想在 Servlet HttpListener SessionInitialize 方法运行时创建 UserContext。 在我想在 Java 类中调用 UserContext 之后。

例子:

受保护的静态地图 userMapList=new HashMap();

此地图保留我的应用程序用户上下文。

但我不知道如何在某些类中实现 active(current) UserContext?

JSF 中的其他示例:

FacesContext 谢谢,

【问题讨论】:

    标签: java httpsession servlets


    【解决方案1】:

    使用 ThreadLocal 类来存储线程特定的值。 因此,当您收到新请求 [这确实是一个新线程] 时,您可以将其转储到 ThreadLocal 对象中 之后,在同一线程上运行的任何类都可以调用 ThreadLocal.get。

    检查它的api@http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html

    【讨论】:

    • 感谢您的回复。但我有一些关于它的问题。 //这是我的上下文类public class Contexts { protected static int value=0; public static ThreadLocal<UserContext> threadLocal=new ThreadLocal<UserContext>(){ protected UserContext initialValue() { return (null);} };; protected static void addUserContext(HttpSession httpSession) { UserContext userContext=new UserContext(httpSession); userContext.getSessionContext().addAttr("value", value++); threadLocal.set(userContext); } public static UserContext getUserContext() { return threadLocal.get(); } }
    • 当我调用 getUserContext 有时它可以给我其他 UserContext 会话。我不知道为什么。如果我调用 System.out.println(Contexts.getUserContext().getSessionContext().getAttr("value"));假设我有 3 个会话。 1.session 值=0 2.session 值=1 3.session 值=2 我关闭了 1 个会话。有时当我调用 3. session value value=0 我不知道为什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多