0

Some months ago I posted my question

Accessing @SessionCoped @Named beans from a HttpSession

which was marked as a duplicate because of the already answered quesiton

Get JSF managed bean by name in any Servlet related class

I tried to access my SessionScoped bean as denoted in the second link like this:

import javax.annotation.ManagedBean;
import javax.enterprise.context.SessionScoped;

@ManagedBean("kauferSessionContainer")
@SessionScoped
public class KauferSessionContainer extends AveSessionContainer {

and then

KauferSessionContainer kauferSessionContainer = (KauferSessionContainer) session.getAttribute("kauferSessionContainer");

but that returned null.

I also tried other combinations, such as

@Named
@SessionScoped
public class KauferSessionContainer extends AveSessionContainer {

and then

KauferSessionContainer kauferSessionContainer = (KauferSessionContainer) session.getAttribute("kauferSessionContainer");

but that also returned null

I inspected in the debugger the content of the session object and ascertained that my KauferSessionContainer is actually there, BUT stored in another way. After some trial and failure I was able to get my object as follows:

Object sessionAttr = session.getAttribute("WELD_S#1");
if (sessionAttr == null) {
    sessionAttr = session.getAttribute("WELD_S#2");
}

if (sessionAttr != null && sessionAttr instanceof SerializableContextualInstanceImpl {
   SerializableContextualInstanceImpl impl = (SerializableContextualInstanceImpl) sessionAttr;
    Object instance = impl.getInstance();
    if (instance instanceof KauferSessionContainer) {

    KauferSessionContainer  = ((KauferSessionContainer)instance);
    ......

The problem with my approach is that I am not sure what identifier my KauferSessionContainer will be stored under - seems it is a dynamic instead of a static name.

I am using JSF 2.3, WildFly 17 and JDK 11.

What I am doing wrong?

Alex Mi
  • 1,409
  • 2
  • 21
  • 35
  • 1
    The duplicate says to use `getAttribute()` when you have a `@javax.faces.bean.ManagedBean` (and thus NOT `@javax.annotation.ManagedBean`). And the duplicate also says to use `@Inject` when you have a `@Named` bean. Please read carefully. – BalusC Oct 11 '22 at 08:49
  • ... but if the @Named bean is a SessionScoped, it might not be a good idea to innject it into a (potantially) application-scoped component, such as a Servlet. Or I am wrong? – Alex Mi Oct 12 '22 at 05:00
  • 1
    You are wrong. `@Inject` injects a proxy instance not the actual instance. It's basically the same way as how good ol' EJBs work: https://stackoverflow.com/q/8658392 – BalusC Oct 12 '22 at 08:06

0 Answers0