如何从 Java 类访问会话

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3748530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:19:53  来源:igfitidea点击:

How to access the session from a Java class

javaservletshttpsession

提问by griegs

I need to write a small Java class that will enable me to add to and read from the current user session.

我需要编写一个小的 Java 类,使我能够添加到当前用户会话并从中读取。

Everything I see refers to Servlets but I'd ideally like to just use a plain old class.

我看到的所有内容都指的是 Servlet,但我最好只使用一个普通的旧类。

Can anyone please help this Java Newbie?

任何人都可以帮助这个Java新手吗?

Thanks

谢谢

回答by Adeel Ansari

Yes, just pass the HttpRequestto your class from your servlet.

是的,只需HttpRequest从您的 servlet传递给您的类。

In your servlet do something like this,

在你的 servlet 中做这样的事情,

cmd.execute(request);

In your class do something like this,

在你的课堂上做这样的事情,

public class Command implements ICommand {
   .
   .
   public void execute(HttpServletRequest request){
      HttpSession sess = request.getSession(false);
   }
   .
   .
   .
}

回答by Sam Day

The general concept of a "Session" is really just a data storage for an interaction between a HTTP client and server. Session management is automatically handled by all HTTP Servlets. What framework?

“会话”的一般概念实际上只是 HTTP 客户端和服务器之间交互的数据存储。会话管理由所有 HTTP Servlet 自动处理。什么框架?

If you're just wanting to store information for a console app to remember information between runs, then consider using Xml to save/load data from a file.

如果您只想为控制台应用程序存储信息以记住运行之间的信息,请考虑使用 Xml 从文件中保存/加载数据。

回答by BalusC

Use a component based MVC framework which abstracts all the ugly Servlet API details away so that you ends up with zero javax.servletimports. Examples of such are JSF2 and Struts2.

使用基于组件的 MVC 框架,该框架将所有丑陋的 Servlet API 细节抽象化,以便最终实现零javax.servlet导入。这样的例子是 JSF2 和 Struts2。

In JSF2 for example, you'd just declare Userclass as a session scoped managed bean:

例如,在 JSF2 中,您只需将User类声明为会话范围的托管 bean:

@ManagedBean
@SessionScoped
public class User {
    // ...
}

Then in the "action" bean which you're using to processing the form submit, reference it as managed property:

然后在您用来处理表单提交的“操作”bean 中,将其引用为托管属性:

@ManagedBean
@RequestScoped
public class SomeFormBean {

    @ManagedProperty(value="#{user}")
    private User user;

    public void submit() {
        SomeData someData = user.getSomeData();
        // ...
    }
}

That's it.

就是这样。

If you'd like to stick to raw Servlet API, then you've to live with the fact that you have to pass the raw HttpServletRequest/HttpServletResponseobjects around. Best what you can do is to homegrow some abstractionaround it (but then you end up like what JSF2/Struts2 are already doing, so why would you homegrow -unless for hobby/self-learning purposes :) ).

如果您想坚持使用原始 Servlet API,那么您必须接受必须传递原始HttpServletRequest/HttpServletResponse对象的事实。你能做的最好的事情就是围绕它自己开发一些抽象(但你最终会像 JSF2/Struts2 已经在做的那样,所以你为什么要自己开发 - 除非出于爱好/自学目的:))。

回答by Ironluca

In general, as mentioned in the other answers, session in many ways acts as a store. So to interact wth a session from another class which is outside of the Servlet/JSP framework the reference to the session in question needs to be procured. There are few ways it can be achieved:

一般来说,如其他答案中所述,会话在许多方面都充当存储。因此,要与来自 Servlet/JSP 框架之外的另一个类的会话进行交互,需要获取对相关会话的引用。有几种方法可以实现:

1) Passing the session as part of a method parameter (already mentioned in other answers) 2) Binding the session to a thread local variable on to the current thread executing (refer ThreadLocal). This method has the advantage of not declaring specific parameters on the method signature of the class that needs to use the session. In addition, if the calling thread goes through a library and then again calls some specific class e.g. Servlet->YourClass0 -> Apache Some Library -> YourClass1, the session will also be available to YourClass1.

1)将会话作为方法参数的一部分传递(已在其他答案中提到) 2)将会话绑定到线程局部变量到当前正在执行的线程(请参阅ThreadLocal)。此方法的优点是不需要在需要使用会话的类的方法签名上声明特定参数。此外,如果调用线程通过一个库,然后再次调用某个特定类,例如 Servlet->YourClass0 -> Apache Some Library -> YourClass1,则会话也将可用于 YourClass1。

However, the thread local also needs to be cleared when the executing thread returns through the initial component (servlet let's say) otherwise there certainly could be memory leaks.

但是,当执行线程通过初始组件(假设是 servlet)返回时,也需要清除线程本地,否则肯定会出现内存泄漏。

In addition, please refer to your specific framework for treatement of sessions, the above mechanism works fine in Tomcat.

另外,请参考您的具体框架处理会话,上述机制在Tomcat中运行良好。