Search code examples
jsfcdisession-scope

How can I use a session bean and deal with many tabs with different parameters?


in a jsf 2.2 application, there is page called test.xhtml that take a paramater called ‘id’ , for example test.xhtml?id=200 . The page is backed by a CDI Session bean named ‘TestBean’. The page has this code to load data:

<f:metadata>
    <f:viewAction action="#{testBean.redirectNoParameters}"></f:viewAction>
</f:metadata>

Now based on the id, the application load a set of fields in the session bean with the right values.

public String redirectNoParameters() {
//Code…
//Load fields
            test = testDao.find(id); 
//Code…
    }

Till now is all good.

Except that when the user opens a new tab in the browser and specify a DIFFERENT id, for example test.xhtml?id=300 . the Session bean override the current values of the previous parameter 200, with the new id 300 values.

So my question is how can I use a session bean and deal with many tabs with different parameters? How can I have a session bean for each tab? If this is not possible than what solution do people use for this kind of scenario ? Thanks.


Solution

  • A @SessionScope Bean is living as long as the users Session is active. (hence the name) - It is shared between Requests and Views, which is the "Problem" you are facing.

    A @RequestScope Bean will be recreated upon every request (No Matter if first-Access or Ajax-Request), which is possible to use for your usecase (reloading data based on resubmitted IDs), but can be optimized. (This would be a traditional Request/Response-Model as known from PHP - JSF offers a better option)

    Your case perfectly matches the @ViewScope. One Bean per View, living as long as the View is present. This would allow you to open an (almost) infinite amount of different Views (hence, the name), each having it's individual set of BackingBeans as long as they are @ViewScope. Multiple "Views" of the same page are possible, each View will maintain the reference to it's dedicated View-Scoped-Beans. (In your example: 2 opened text.xhtml pages and therefore 2 active instances of TestBean, each having its own ID)