JEE6 应用程序会话范围对象
我对 JEE6 还很陌生,因为我来自遗留系统上的 Servlet + JSP 风格的开发。在我开发的应用程序中,我们只需将对象放入以常量字符串为键的各种提供的范围(请求、会话和应用程序)中。例如,表示当前登录用户的用户对象将位于“current_user”下键入的会话范围内。
当用户登录时,我在新的 JEE6 应用程序中执行了相同的操作,User 对象被绑定到会话范围中。我想知道是否有更好、更 EE 的方法来处理这个问题?
我遇到的问题是,现在我已经将用户存储在会话中,再次访问它很尴尬。我可以通过 JNDI 查找或使用几行涉及 FacesContext 的样板代码来获取它,但这两者都不是很优雅。
如果我可以将对象注入到字段或方法中,而不是到处都是样板代码(在一些地方需要用户对象),那就太好了。毕竟,会话中只能有一个对象绑定到特定名称,因此我所要求的内容不应该有任何歧义。这可能吗?
I'm still pretty new to JEE6 having come from a Servlets + JSP style of development on legacy systems. In the applications I worked on we would just throw objects into the various supplied scopes (request, session and application) keyed on a constant String. For example, the User object that represented the currently logged in user would be in the session scope keyed under "current_user".
I've done the same in our new JEE6 application, when the user logs in the User object is bound into the session scope. I'm wondering though if there is a better, more EE, way of handling this?
The problem I'm having is that now I've got the User stored in the session it's awkward to get access to it again. I can get it via JNDI look up or with a few lines of boiler plate code involving FacesContext but neither are very elegant.
Rather than boiler plate code all over the place (the User object is need in a few places) it would be great if I could just get the object injected into a field or method. After all there can only be one object in the session bound to a particular name so there shouldn't be any ambiguity about what I'm asking for. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许 CDI 能帮上忙?
您能否将实现 User 对象的方式定义为一个 main 方法?
如果是这样,并且您正在使用 Java EE 6 环境,则可以使用 Producer 方法。这两行之间的内容:
然后在您想要使用此类的地方,只需注入它(在字段或方法中)并使用它:
您需要记住将 beans.xml 文件添加到您的类路径中,因为没有 CDI 将不适用于您的模块。
Maybe the CDI could be of any help?
Could you define the way you achieve the User object into one, main method?
If so, and you're working with Java EE 6 environment, you could use the Producer method. Something between these lines:
Then in the place you want to use this class you just Inject it (in the field or method) and use it:
You need to remember to add the beans.xml file to your classpath, as without the CDI will not work for your module.