简体   繁体   English

将无状态bean封装在有状态会话中

[英]Encapsulating stateless beans inside a stateful session

I have a Java EE application using EJBs, and perform most of the functions through Stateless EJBs. 我有一个使用EJB的Java EE应用程序,并通过无状态EJB执行大多数功能。

I have a requirement for all users to also have an active session, and I'm wondering what the best way of using the beans are. 我要求所有用户也都有一个活跃的会话,我想知道使用bean的最佳方法是什么。

Currently, I have a command line client which uses the stateless beans directly in addition to logging into the system with the stateful bean. 当前,我有一个命令行客户端,除了使用有状态Bean登录系统之外,它还直接使用无状态Bean。

I'm wondering if I should have the client perform all functions through the stateful bean, that way no functions can be performed unless an active session exists. 我想知道是否应该让客户端通过有状态Bean执行所有功能,这样除非存在活动会话,否则无法执行任何功能。
This makes more sense to me personally. 就我个人而言,这更有意义。

I'm just not quite sure what design is 'right' or what is the better design. 我只是不太确定哪种设计是“正确的”或什么是更好的设计。
If I continue to have the client use the stateless beans, then I'll have to have a way for those stateless beans to check if the client has an active session. 如果我继续让客户端使用无状态Bean,则必须为这些无状态Bean提供一种方法来检查客户端是否具有活动会话。

A session exists anyway even if you're only invoking stateless beans. 即使您仅调用无状态Bean,会话也仍然存在。 The choice on whether to invoke a stateless or stateful bean should mater only whether you need to keep state between method invocations. 是否调用无状态或有状态Bean的选择仅应在是否需要在方法调用之间保持状态的情况下进行。 Try injecting the SessionContext and notice that there will be a principal, even if it's anonymous. 尝试注入SessionContext并注意会有一个委托人,即使它是匿名的也是如此。

If your requirement is an authenticated user, a stateless session bean is fine: 如果您的要求是经过身份验证的用户,那么无状态会话bean可以:

  • You can call SessionContext.getCallerPrincipal() in the EJB (for logging purposes etc.) 您可以在EJB中调用SessionContext.getCallerPrincipal() (用于记录等)。
  • You can impose authorization declaratively (using the @RolesAllowed annotation on EJB methods) 您可以声明性地施加授权(在EJB方法上使用@RolesAllowed批注)

so I don't see a reason to switch to stateful session beans. 因此我看不出有理由切换到有状态会话Bean的原因。 It might not be relevant, but a stateful session bean consumes resources on the server side, so there should be a compelling reason to do so. 可能不相关,但是有状态会话Bean会消耗服务器端的资源,因此应该有充分的理由这样做。

A related question When to use Stateful session bean over Stateless session bean? 相关问题何时在无状态会话Bean上使用有状态会话Bean? received no answers up to today, and I consider no answer in this case to be an answer as well . 没有收到任何答案到今天为止,我认为在这种情况下没有答案的 一个答案为好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM