Rectangle 27 36

Depends on who's managing the bean.

If it's JSF via @ManagedBean, then it defaults to @RequestScoped, as mentioned in the javadoc:

If the scope annotations are omitted, the bean must be handled as if the RequestScoped annotation is present

If it's CDI via @Named, then it defaults to @Dependent, as mentioned in Weld documentation:

Finally, CDI features the so-called dependent pseudo-scope. This is the default scope for a bean which does not explicitly declare a scope type.

The effect is that the bean instance is newly created on every single EL expression. So, imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. In effects, this behaves the same as JSF @NoneScoped. This confirms the symptoms you're seeing.

If it's Spring via @Component, then it defaults to @Scope("singleton"), as mentioned in javadoc:

"singleton"

In effects, this behaves the same as JSF @ApplicationScoped and CDI @ApplicationScoped.

Netbeans has got nothing to do with it. It's just an editing tool like notepad but then with 1000+ extra features.

@BalusC I'm confused ... you said that default scope for ManagedBean is NoneScoped, but documentation says that it's RequestScoped: "If the scope annotations are omitted, the bean must be handled as if the RequestScoped annotation is present" docs.oracle.com/javaee/6/api/javax/faces/bean/ManagedBean.html

But, i have seen several documents which say that "@Dependent scoped beans, inherit the scope of the bean they injected to" in this link, so if the bean that is injected to has a session scope, then a separate bean won`t be generated for each EL.

@NPE: It will be if you reference it directly in EL as in #{dependentScopedBean} instead of as a property of a session scoped bean as in #{sessionScopedBean.dependentScopedBean}.

What is the default Managed Bean Scope in a JSF 2 application? - Stack...

jsf
Rectangle 27 35

Depends on who's managing the bean.

If it's JSF via @ManagedBean, then it defaults to @RequestScoped, as mentioned in the javadoc:

If the scope annotations are omitted, the bean must be handled as if the RequestScoped annotation is present

If it's CDI via @Named, then it defaults to @Dependent, as mentioned in Weld documentation:

Finally, CDI features the so-called dependent pseudo-scope. This is the default scope for a bean which does not explicitly declare a scope type.

The effect is that the bean instance is newly created on every single EL expression. So, imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. In effects, this behaves the same as JSF @NoneScoped. This confirms the symptoms you're seeing.

If it's Spring via @Component, then it defaults to @Scope("singleton"), as mentioned in javadoc:

"singleton"

In effects, this behaves the same as JSF @ApplicationScoped and CDI @ApplicationScoped.

Netbeans has got nothing to do with it. It's just an editing tool like notepad but then with 1000+ extra features.

@BalusC I'm confused ... you said that default scope for ManagedBean is NoneScoped, but documentation says that it's RequestScoped: "If the scope annotations are omitted, the bean must be handled as if the RequestScoped annotation is present" docs.oracle.com/javaee/6/api/javax/faces/bean/ManagedBean.html

But, i have seen several documents which say that "@Dependent scoped beans, inherit the scope of the bean they injected to" in this link, so if the bean that is injected to has a session scope, then a separate bean won`t be generated for each EL.

@NPE: It will be if you reference it directly in EL as in #{dependentScopedBean} instead of as a property of a session scoped bean as in #{sessionScopedBean.dependentScopedBean}.

What is the default Managed Bean Scope in a JSF 2 application? - Stack...

jsf
Rectangle 27 36

@Named gives a CDI managed bean an EL name to be used in view technologies like JSF or JSP. Note that in a CDI application you don't need the @Named annotation to make a bean managed by CDI (thanks to @Karl for his comment).

@ManagedBean makes the bean managed by JSF and you can:

  • inject it into other @ManagedBean annotated beans (but not into @Named beans!)
  • access it from your views via expression language

See this related question for further information how injection works among both kind of beans.

Note that there is also a difference with the scope of the beans. They come from different packages but are named identically (JSF: javax.faces.bean, CDI: javax.enterprise.context , so it is often a source of error and confusion if you include the wrong class.

From my experience: You should use CDI beans whenever possible since they are more flexible than JSF managed beans. Only drawback is that CDI doesn't know a view scope, so you either need to fall back to @ManagedBean or use some third party extension like Seam.

+1. @matt: I think RequestScoped + KeepAlive = ViewScoped so that can be also be used with @Named. Am i correct?

@matt: yes in richfaces3.3.3 along with JSF2.0 I am using keepalive along with request scope.

@MattHandy Regarding the bean and Named I think you are a bit misleading. The bean is already managed by cdi and can be injected etc. Your description sounds more like Name from Seam 2. Named is for EL. Please correct me if I am wrong

jsf 2 - Difference between @Named and @ManagedBean annotations in JSF2...

jsf-2 dependency-injection el tomcat7
Rectangle 27 1

You have several possibilities to initialize an entity. There is the EntityHome class that you can extend for an entity. It's the default implementation of handling entities for an editor. It is also used if you use seam-gen to create your application.

@Name("queryHome")
@Scope(ScopeType.CONVERSATION)
public class QueryHome extends EntityHome<Query> {
    /*
     * (non-Javadoc)
     * @see org.jboss.seam.framework.Home#createInstance()
     */
    @Override
    public Query createInstance() {
        Query query = super.createInstance();
        query.setUser(loggedUser);
        query.setCreationDate(new Date());
        query.setLastExecutionDate(new Date());
        return query;
    }
}

And you will be calling queryHome.getInstance(). If the id property in entityHome is set it will try to load the entity with this id from the database, and if there is no id it will call createInstance(). This is how i use it normally.

You can also create a factory annotated method in a seam managed bean. There you can do whatever you like.

@Name("CreationFactory")
@Scope(ScopeType.STATELESS)
pulic class CreationFactory {

    @Factory("createNewTask")
    public Task createTask() {
        Task task = new Task();
        task.sometext = "sometext";
        return task;
    }
}

I normally do not access or create a bean directly but i use a manager component like the entityhome to do it. You can simplify the access with a factory, but this is explained in the Seam documentation.

martin, thanks for the advice, the first way works just fine - though I'm not sure in an EJB scenario, extending EntityHome as a session bean would work (does it?) The second way, can you give me an idea how the method createTask would be invoked?

Porting functionality of a managed bean while migrating from Core JSF ...

jsf seam managed-bean postconstruct
Rectangle 27 11

All HTTP session attributes will be serialized as well, including session scoped JSF managed beans. Any bean properties which are not serializable will be skipped. During deserialization on another node, you will face a NotSerializableException on all bean properties which are not serializable. Marking the property transient will fix that exception, but the property will still remain null after deserialization.

Nope. It won't be re-injected. You have to take care of this manually in case of @ManagedProperty.

One somewhat naive and error-prone way is getting rid of @ManagedProperty and performing lazy loading in the getter (thus, act like a proxy yourself):

private transient ApplicationBean applicationBean;

public ApplicationBean getApplicationBean() {
    if (applicationBean == null) { 
        FacesContext context = FacesContext.getCurrentInstance();
        applicationBean = context.getApplication().evaluateExpressionGet(context, "#{applicationBean}", ApplicationBean.class);
    }

    return applicationBean;
}

and use the getter throughout the code instead referencing the property directly.

The better way is to make it an EJB or a CDI managed bean. They're fully transparently created and injected as serializable proxies and you never need to worry about serialization on them.

import javax.ejb.Singleton;

@Singleton
public class ApplicationBean {
    // ...
}
import javax.ejb.EJB;
import.javax.faces.bean.ManagedBean;
import.javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class SessionBean implements Serializable {

    @EJB
    private ApplicationBean applicationBean;

    // ... (no setter/getter necessary!)
}
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@SessionScoped
public class SessionBean implements Serializable {

    @Inject
    private ApplicationBean applicationBean;

    // ... (also here, no setter/getter necessary!)
}

jsf - Injecting non-serializable application scoped bean as managed pr...

jsf session cluster-computing
Rectangle 27 419

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

@Cold: that's an old CDI scope and in JSF 2.2 substituted with @FlowScoped (no need to manually start/stop it).

jsf - How to choose the right bean scope? - Stack Overflow

jsf jsf-2 scope managed-bean
Rectangle 27 419

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

@Cold: that's an old CDI scope and in JSF 2.2 substituted with @FlowScoped (no need to manually start/stop it).

jsf - How to choose the right bean scope? - Stack Overflow

jsf jsf-2 scope managed-bean
Rectangle 27 419

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

@Cold: that's an old CDI scope and in JSF 2.2 substituted with @FlowScoped (no need to manually start/stop it).

jsf - How to choose the right bean scope? - Stack Overflow

jsf jsf-2 scope managed-bean
Rectangle 27 419

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

@Cold: that's an old CDI scope and in JSF 2.2 substituted with @FlowScoped (no need to manually start/stop it).

jsf - How to choose the right bean scope? - Stack Overflow

jsf jsf-2 scope managed-bean
Rectangle 27 407

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

@Cold: that's an old CDI scope and in JSF 2.2 substituted with @FlowScoped (no need to manually start/stop it).

jsf - How to choose the right bean scope? - Stack Overflow

jsf jsf-2 scope managed-bean
Rectangle 27 407

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

@Cold: that's an old CDI scope and in JSF 2.2 substituted with @FlowScoped (no need to manually start/stop it).

jsf - How to choose the right bean scope? - Stack Overflow

jsf jsf-2 scope managed-bean
Rectangle 27 61

Never use java.util.Timer in Java EE

As to spawning a thread from inside a JSF managed bean, it would only make sense if you want to be able to reference it in your views by #{managedBeanName} or in other managed beans by @ManagedProperty("#{managedBeanName}"). You should only make sure that you implement @PreDestroy to ensure that all those threads are shut down whenever the webapp is about to shutdown, like as you would do in contextDestroyed() method of ServletContextListener (yes, you did?). See also Is it safe to start a new thread in a JSF managed bean?

As to using java.util.Timer in a JSF managed bean, you should absolutely not use the old fashioned Timer, but the modern ScheduledExecutorService. The Timer has the following major problems which makes it unsuitable for use in a long running Java EE web application (quoted from Java Concurrency in Practice):

  • Timer is sensitive to changes in the system clock, ScheduledExecutorService isn't.
  • Timer has only one execution thread, so long-running task can delay other tasks. ScheduledExecutorService can be configured with any number of threads.
  • Any runtime exceptions thrown in a TimerTask kill that one thread, thus making Timer dead, i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want. Task which threw exception will be canceled, but other tasks will continue to run.

Apart from the book quotes, I can think of more disadvantages:

If you target Java EE 6 or newer (e.g. JBoss AS, GlassFish, TomEE, etc and thus not a barebones JSP/Servlet container such as Tomcat), then use a @Singleton EJB with a @Schedule method instead. This way the container will worry itself about pooling and destroying threads via ScheduledExecutorService. All you need is then the following EJB:

@Singleton
public class BackgroundJobManager {

    @Schedule(hour="0", minute="0", second="0", persistent=false)
    public void someDailyJob() {
        // Do your job here which should run every start of day.
    }

    @Schedule(hour="*/1", minute="0", second="0", persistent=false)
    public void someHourlyJob() {
        // Do your job here which should run every hour of day.
    }

    @Schedule(hour="*", minute="*/15", second="0", persistent=false)
    public void someQuarterlyJob() {
        // Do your job here which should run every 15 minute of hour.
    }

}

This is if necessary available in managed beans by @EJB:

@EJB
private BackgroundJobManager backgroundJobManager;

Without EJB, you'd need to manually work with ScheduledExecutorService. The application scoped managed bean implementation would look something like this:

@ManagedBean(eager=true)
@ApplicationScoped
public class BackgroundJobManager {

    private ScheduledExecutorService scheduler; 

    @PostConstruct
    public void init() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new SomeDailyJob(), 0, 1, TimeUnit.DAYS);
    }

    @PreDestroy
    public void destroy() {
        scheduler.shutdownNow();
    }

}
SomeDailyJob
public class SomeDailyJob implements Runnable {

    @Override
    public void run() {
        // Do your job here.
    }

}

If you don't need to reference it in the view or other managed beans at all, then better just use ServletContextListener to keep it decoupled from JSF.

@WebListener
public class BackgroundJobManager implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new SomeDailyJob(), 0, 1, TimeUnit.DAYS);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

I remembered to use contextDestroyed() :P Noted about the ScheduledExecutorService. I would only need it in order to display the time of the last scheduled execution and kill/re run it. Thanks once again!

Timer
ScheduledExecutorService

@BalusC What if one would need reference to another CDI bean from the scheduler? - What approached is best to use? - Thanks.

@timbooo: just @Inject it the usual way.

@BalusC But injection a session scoped bean into a ejb Singleton is not possible, since there is no active session context. What would be a possible workaround for that?

jsf 2 - Spawning threads in a JSF managed bean for scheduled tasks usi...

jsf jsf-2 timer scheduled-tasks
Rectangle 27 3

This would be the best way, in my opinion. Is there a reason you would like to avoid this? You can, as harto suggests, use component binding, but (as Vinegar points out) you gain nothing from this approach.

<h:inputText id="username" value="some_value" required="true" />

If you want to read the above value, it is possible to read it directly from the request parameters. The ExternalContext encapsulates the underlying container API and can be accessed in a managed bean like so:

FacesContext facesContext = FacesContext
    .getCurrentInstance();
ExternalContext extContext = facesContext
    .getExternalContext();
Map<String, String> params = extContext
    .getRequestParameterMap();

But, aside from violating the model-view-presenter contract, you can run into some practical problems. The parameter key may not be "username", but might be something like "j_id_jsp_115874224_691:username", depending on whether you make the component a child of any NamingContainers (like UIForm - see the prependId attribute) or if the view is namespaced. Hard-coding this value anywhere is probably a bad idea. You can read about the relationship between JSF component IDs and rendered HTML IDs here. If you want to use UIComponent.getClientId to generate the the key, you are back to component binding because you need to get a reference to the component.

Another question is it possible to access to the session variables in managed bean..?

Thank you very much for taking time and explaining things to me. I really appreciate it. The reason i asked is because JSF is first java framework i am studying and I really like it. The question was for education purpose(prior to it i tryed to goodle, but didnot find no good explanation), in reall application i am not going use it like that, but i wanted to know how it can be done.

Ah, I quite forgot about the naming issue. Thanks for pointing out. Futher dealing with Maps is a better idea. +1

java - JSF inputText and Sessions in jsf managed bean - Stack Overflow

java jsp jsf
Rectangle 27 4

You don't need to create it yourself. The servletcontainer will do it automatically for you on demand. In other words, whenever you (or JSF) need to set an object in the session scope, then the servletcontainer will automatically create the session. In a JSF web application, this will happen when you

  • Reference a @SessionScoped or @ViewScoped managed beanfor the first time.
ExternalContext#getSession()
true
  • Store an object in session map by ExternalContext#getSessionMap() for the first time.
  • Return a page with a <h:form> for the first time while the state saving method is set to "server".
ExternalContext#invalidateSession()
public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

Remember to send a redirect afterwards, because the session objects are still available in the response of the current request, but not anymore in the next request.

Just make it a property of a @SessionScoped managed bean. Alternatively, you can also manually manipulate the ExternalContext#getSessionMap(), yes.

How to create, access and destroy session in JSF managed bean? - Stack...

jsf session scope invalidate
Rectangle 27 2

In the latter case that some_value is not bean managed, IMHO. Nonetheless, you can read that. Do something like this,

FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest request =
      (HttpServletRequest)ctx.getExternalContext().getRequest(); 
request.getParameter("username");
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest request =
      (HttpServletRequest)ctx.getExternalContext().getSession(false);

The parameter name may not be "username" (see my answer); also, you can avoid casting to the servlet API if you want to.

java - JSF inputText and Sessions in jsf managed bean - Stack Overflow

java jsp jsf
Rectangle 27 2

A common way to read a component value is to create a binding to the component in your managed-bean, and read the value from it.

<h:inputText id="username" value="some_value" required="true"
    binding="#{mylogin.usernameField}" />

Then, in the managed-bean:

private UIInput usernameField;

public void setUsernameField(UIInput usernameField) { 
    this.usernameField = usernameField;
}
public UIInput getUsernameField() { 
    return usernameField; 
}
Object value = usernameField.getValue();

That would be component binding. Not a good idea, IMHO. Thats the reason I didn't mention it. But yes its the way. Actually in this case you lose the simplicity of POJO, and tie your bean completely with JSF.

Sure - it's not practical unless you wanted to do something else with the component. The best way to do it is well-known - just use a value binding expression.

java - JSF inputText and Sessions in jsf managed bean - Stack Overflow

java jsp jsf
Rectangle 27 2

Here is my code for start and end time pickers with client side validation, hope it helps.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:rich="http://richfaces.org/rich"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <title>TimePicker</title>
    <script src="./resources/js/timeValidator.js"></script>
</h:head>
<h:body>
    <rich:panel>
        <h:form id="form1">
            <h:panelGrid border="1" rules="all" columns="2" cellpadding="10">
                <h:panelGrid columns="2">
                    <f:facet name="header">
                        <h:outputText value="Start time" />
                    </f:facet>
                    <h:outputLabel value="HH:" />
                    <rich:inputNumberSpinner id="h1" minValue="0" maxValue="23"
                        onchange="validate('form1:h1','form1:m1','form1:h2','form1:m2',true)" />
                    <h:outputLabel value="MM:" />
                    <rich:inputNumberSpinner id="m1" minValue="0" maxValue="59"
                        onchange="validate('form1:h1','form1:m1','form1:h2','form1:m2',true)">
                    </rich:inputNumberSpinner>
                </h:panelGrid>
                <h:panelGrid columns="2">
                    <f:facet name="header">
                        <h:outputText value="End time" />
                    </f:facet>
                    <h:outputLabel value="HH:" />
                    <rich:inputNumberSpinner id="h2" minValue="0" maxValue="23"
                        onchange="validate('form1:h1','form1:m1','form1:h2','form1:m2',false)" />
                    <h:outputLabel value="MM:" />
                    <rich:inputNumberSpinner id="m2" minValue="0" maxValue="59"
                        onchange="validate('form1:h1','form1:m1','form1:h2','form1:m2',false)" />
                </h:panelGrid>
            </h:panelGrid>
        </h:form>
    </rich:panel>
</h:body>
</html>
function validate(stHourId, stMinId, enHourId, enMinId, stChanged) {
    var stHour = RichFaces.$(stHourId).getValue();
    var stMin = RichFaces.$(stMinId).getValue();
    var enHour = RichFaces.$(enHourId).getValue();
    var enMin = RichFaces.$(enMinId).getValue();
    if (stChanged) {
        if (enHour < stHour) {
            enHour = stHour;
        } else if (enHour == stHour && enMin < stMin) {
            enMin = stMin;
        }
    } else {
        if (enHour < stHour) {
            stHour = enHour;
        } else if (enHour == stHour && enMin < stMin) {
            stMin = enMin;
        }
    }
    RichFaces.$(stHourId).setValue(stHour);
    RichFaces.$(stMinId).setValue(stMin);
    RichFaces.$(enHourId).setValue(enHour);
    RichFaces.$(enMinId).setValue(enMin);
}

Thanks for sharing your code, that's exactly what I was doing! I've also realized I have to dynamically change both the min and max values, and I think the only way I can achieve that is to get back to the server everytime a new hour is selected (the minute range depends on the selected hour -> basically the start time and the end time do not use the full range of minutes), change the min and max values for the minute spinner and refresh it. I found a way to solve it in javascript, but it didn't work when you had either the DOWN or UP button always pressed...Thanks again.

How to integrate a time picker in Richfaces and bind it to a jsf manag...

jsf richfaces timepicker managed-bean
Rectangle 27 2

rich:calendar is for choosing date and its time picker is optional, I think you should write it yourself, just put two rich:inputNumberSpinner for hours and minutes.

<rich:inputNumberSpinner value="#{myBean.hours}" minValue="0" maxValue="23" />
<rich:inputNumberSpinner value="#{myBean.minutes}" minValue="0" maxValue="59" />

In MyBean class define two integer properties, hours and minutes; then add getters and setters for them.

Thanks for your reply. I was already thinking about that kind of solution, but the fact that the "00" minute would be displayed as "0" worries me a bit. Do you think it could be a problem for the look and feel of my web app? Based on my requirements I actually need to display two time pickers (Start Time and End Time), and dynamically update their value based on the user selection. E.g.: if the user selects a Start Time greater than the End Time, the latter should be updated with the same value as the Start Time. How can I achieve this using some javascript? Thanks.

I'm working on a web application that needs a component for choosing time like you, and I could not found anything better than inputNumberSpinner for this, unfortunately richfaces 4.0 does not support number formatting for inputNumberSpinner but I think it is not a problem in look and feel of my web app. For your second question, I prefer to change minimum and maximum attributes in myBean by ajax request because I don't like to write javascript code when JSF, Richfaces and ManagedBeans exist!

Thanks. I agree with your point: min and max values should be set through ajax requests and managed beans. However, in my case I need to update their value dynamically based on the user selection. If the start time (which is a composition of two input spinners) is greater then the end time (composition of other two spinners), then the latter should be updated accordingly (e.g. make it bigger). I think ajax shouldn't be used in this case because you don't want to get back to the server each time the user clicks on the spinner; js is more appropriate for this "presentation feature".

Sorry, I made a mistake there. I meant to say I have to dynamically change the current value of both the start time and end time based on the user selection. Min and max values are set only once through ajax requests. Javascript is used to update the current value of the input spinners when the user clicks on them.

How to integrate a time picker in Richfaces and bind it to a jsf manag...

jsf richfaces timepicker managed-bean
Rectangle 27 1

how to seperate getters and setters from managed bean in JSF?

@Named
@ViewScoped
public class LoginModel implements Serializable {
    private String userName;
    private String password;

    //Getters and setters ...
}

@Named
@ViewScoped
public class LoginController implements Serializable {

    @Inject
    private LoginModel loginData;

    public String logIn(){
        if(isLoginDataValid(loginData)){
            return "index.xhtml";
        }
    }
}
javax.faces.view.ViewScoped
javax.faces.bean.ViewScoped
<h:form>
    <table>
        <tr>
            <td>Username:</td>
            <td>
                <h:inputText value="#{loginModel.userName}"/>
            </td>
        </tr>
        <tr> 
            <td>Password:</td>
            <td>
                <h:inputText value="#{loginModel.password}"/>
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <h:commandButton value="Login" action="#{loginController.logIn}"/>          
            </td>
        </tr>
    </table>
</h:form>

Please make sure you use javax.faces.view.ViewScoped as the annotation. Do not use javax.faces.bean.ViewScoped.

javax.faces.view.ViewScoped is not available for me. Am i need to add any jar file? please help me you can solve my problem.

If you use maven add the javaee-api as a dependency with scope 'provieded'. If you use Java EE 7 mvnrepository.com/artifact/javax/javaee-api/7.0. If not you can download it from the same link and add it to the classpath.

java - How to separate getters and setters from managed bean in JSF? -...

java jsf javabeans getter-setter
Rectangle 27 1

@ViewScoped: a bean in this scope lives as long as you're interacting with the same JSF view in the browser window/tab. It get created upon a HTTP request and get destroyed once you postback to a different view. It doesn't immediately get destroyed when you leave/close the view by a GET Request, but it is not accessible the usual way anymore. JSF stores the bean in the UIViewRoot#getViewMap() with the managed bean name as key, which is in turn stored in the session. You need to return null or void from action (listener) methods to keep the bean alive. Use this scope for more complex forms which use ajax, data tables and/or several rendered/disabled attributes whose state needs to be retained in the subsequent requests within the same browser window/tab (view).

@SessionScoped: a bean in this scope lives as long as the HTTP session lives. It get created upon the first HTTP request involving this bean in the session and get destroyed when the HTTP session is invalidated (or when you manually remove the bean from the session map). JSF stores the bean as an attribute of HttpSession with the managed bean name as key. It is also available by ExternalContext#getSessionMap(). Use this scope for pure session-scoped data which can safely be shared among all browser windows/tabs (views) within the same session. For example, the logged-in user, the user preferences such as user-specific settings and the chosen language/locale, etc.

ViewScoped beans are stored in the UIViewRoot which in turn is stored in the users session, thus the ViewScoped beans are indirectly also stored in session. After the session expires and is destroyed, the ViewScoped beans get destroyed as well and if you are referencing something in your code of that LoginBean that is expecting state, or perhaps you are using a third party component that requires state (Eg. a4j), then that can explain the wierdness.

I suggest switching to RequestScoped for your LoginBean. I have never run into a situation where I needed ViewScoped backing beans for logging into an application.

>> the ViewScoped is not for the LoginBean. There is a page that is not required for user to login. It is like a search page where a lot of ajax behaviour inside. That's why I used ViewScoped for that. As per your explaination, 'ViewScoped beans are indirectly also stored in session. After the session expires and is destroyed, the ViewScoped beans get destroyed as well'. Currently, what i did is manipulating the session count in JavaScript which I think is not the best solution to force the user to reload the page back after 30 minutes.

a4j not working after session timeout in jsf and managed bean viewscop...

jsf