Search code examples
cssjsfelview-scope

How to get @ViewScoped bean property in CSS resource?


I have a @ViewScoped bean:

@Named
@ViewScoped
public class testBean implements Serializable {
    private static final long serialVersionUID = 1L;
    private String color;

    @PostConstruct
    public void postConstruct() {
        color = "red";
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

In my JSF page I can access the property color by #{testBean.color}, but in my CSS resource it doesn't work.

html, body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    border: 0;
    background-color: #{testBean.color};
}

It throws the below exception:

org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type javax.faces.view.ViewScoped
    at org.jboss.weld.manager.BeanManagerImpl.getContext(BeanManagerImpl.java:680) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:79) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:78) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at com.unifik.core.subdomain.admin.WidgetLoginBean$Proxy$_$$_WeldClientProxy.getWidgetLogin(Unknown Source) [classes:]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_67]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_67]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_67]
    at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_67]
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:363) [jboss-el-api_3.0_spec-1.0.3.Final.jar:1.0.3.Final]
    ... 46 more

If I change @ViewScoped to @SessionScoped, then it works, but I do not want that.


Solution

  • The bean cannot be view scoped for that. The CSS file is requested during a completely separate GET request initiated by the webbrowser when it's being instructed to download the CSS file after inspecting the retrieved HTML page. This specific request for the CSS file knows nothing about the JSF view state and hence any EL expressions referencing a JSF view scoped bean just won't be able to find the desired bean as there's no means of a JSF view state anywhere during processing the request for the CSS file.

    Either choose another bean scope, or inline it in a <style> element in the HTML page. A request, session or application scoped bean should work. See also How to choose the right bean scope?