Search code examples
javajsfjsf-2scopejava-ee-6

holding variables in session scope without making them static?


This is a rookie question, sorry.

I developed a jsf-2 app (on Tomcat) which has a big controller bean declared in session scope.

Now, the mistake I made was to put all session scoped variables in this bean as static variables, thinking they would not be shared between different instances of the app. But they are - static variables are shared across all instances of the app on a same JVM, which makes sense actually. Anyway, all my code is currently like that:

@SessionScoped
@ManagedBean
public ControllerBean{
static private String aString = "session wide value for a string";
//static getter and setter for astring

}

@viewscoped
@ManagedBean
public class OneRandomViewScopedBean{
String oneString = ControllerBean.getAString();
//operations on this string...
ControllerBean.setAString(newValueForString);
} 

Could I get pointers as to how I should refactor my code to remove the static variables in my ControllerBean? I suppose the solution is dead simple but I can't see it now.

Note: I don't need to persist the data because the volumes are small and they can vanish after the app is closed

Thx!


Solution

  • Remove the static modifier (that was indeed a huge mistake; this problem is not JSF specific, but just basic Java. I'd really invest some more time in learning basic Java before continuing with JSF) and use @ManagedProperty to inject other beans or its properties.

    @ManagedBean
    @SessionScoped
    public class ControllerBean {
    
        private String aString = "session wide value for a string";
        // Non-static getter and setter for aString.
    
        // ...
    }
    
    @ManagedBean
    @ViewScoped
    public class OneRandomViewScopedBean {
    
        @ManagedProperty("#{controllerBean}")
        private ControllerBean controllerBean;
        // Setter for controllerBean. Getter is not mandatory.
    
        public void someAction() {
            controllerBean.setAString(newValueForString);
        }
    
        // ...
    } 
    

    See also: