1

In a JSF 1.2 application, can I override a session-scoped Managed Bean returned with a subclass?

Class structure

I have a session-scoped Managed Bean, MainViewMB, and its subclass, RestrictedViewMB:

UML: <<ManagedBean>> MainViewMB extended by RestrictedViewMB

faces-config.xml

<managed-bean>
  <managed-bean-name>mainViewMB</managed-bean-name>
  <managed-bean-class>com.example.MainViewMB</managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Problem statement

The EL expression #{mainViewMB} returns an instance of MainViewMB.

I would like to rebind the name #{mainViewMB} with an instance of RestrictedViewMB, so that the EL expression #{mainViewMB} returns an instance of the subclass for the rest of the session.

Is there a way to accomplish my goal?

Motivating example

MainViewMB handles the GUI logic behind the application's main page. When a user enters the application from a special-purpose login page, I need to provide a restricted, simplified view of the main page. Overriding some of MainViewMB's properties in a subclass seems the obvious solution.

Community
  • 1
  • 1
Danilo Piazzalunga
  • 7,590
  • 5
  • 49
  • 75

1 Answers1

2

Do it manually at the moment you can/need to do it.

externalContext.getSessionMap().put("mainViewMB", new RestrictedViewMB());

This puts a new instance of RestrictedViewMB in the session scope with the name mainViewMB, effectively making it a session scoped managed bean.

You only need to take into account that managed properties and @PostConstruct/@PreDestroy are not invoked this way, you'd also have to do it manually.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Will `#{mainViewMB}` work? Is any other action required to make it work with EL? – Danilo Piazzalunga Nov 26 '13 at 19:05
  • 3
    Yes, otherwise this answer was pointless. Nope, it completely overrides any existing session attribtues, including JSF managed beans. Do you by the way understand how JSF creates and manages beans? JSF puts session scoped managed beans exactly the same way in the session map with the managed bean name as key. You're here just repeating JSF's job, but then with a different instance. – BalusC Nov 26 '13 at 19:06
  • Yes and no. I understand how EJB dependency injection works, and I understand JSP/Servlet web application scopes, but my understanding of JSF has a few gaps. – Danilo Piazzalunga Nov 26 '13 at 21:01