when to use Serializable backing bean in JSF?
is there any factors to go for serialization like View Scope, Session Scope, Application Scope or is anything else which requires bean to be serialized.
I'd say that session-scoped beans are eligible for serialization, because the the servlet container tries to serialize everything in the session in case it (the container) is restarted.
Related
Is is possible to inject JSF Managed Bean into an EJB? I have injected JSF Managed Beans in to another JSF Managed Bean as a #ManagedProperty. But when I do the same to the EJB, I get a null point exception.
No, that's not possible. The #ManagedProperty works inside #ManagedBean classes (JSF managed beans) only. You can only use #EJB or #Inject to inject another EJB or a CDI managed bean (a #Named class).
However, it makes design technically no sense to inject a front-end class like a JSF or CDI managed bean in a business service class like an EJB. An EJB should be designed in such way that it can without changes be reused together a completely different front-end like JAX-RS webservice or even a plain vanilla servlet. An EJB should absolutely not have any javax.faces.* imports/dependencies (like as that it should not have any javax.ws.rs.* nor javax.servlet.* ones).
If you intend to pass data from the JSF managed bean to an EJB, then just pass it as method argument. Such data is usually in flavor of a JPA #Entity or at least an ID/keyword which returns an entity.
I noticed that there are different bean scopes like:
#RequestScoped
#ViewScoped
#FlowScoped
#SessionScoped
#ApplicationScoped
What is the purpose of each? How do I choose a proper scope for my bean?
Introduction
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.
#Request/View/Flow/Session/ApplicationScoped
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.
See also:
Difference between View and Request scope in managed beans
Advantages of using JSF Faces Flow instead of the normal navigation system
Communication in JSF2 - Managed bean scopes
#CustomScoped/NoneScoped/Dependent
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.
See also:
Expire specific managed bean instance after time interval
what is none scope bean and when to use it?
What is the default Managed Bean Scope in a JSF 2 application?
Flash scope
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.
See also:
How to show faces message in the redirected page
Pass an object between #ViewScoped beans without using GET params
CDI missing #ViewScoped and #FlashScoped
Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using #ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.
From JSF 2.3 here are scopes that can be used on JSF Backing Beans:
1. #javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.
2. #javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.
3. #javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.
4. #javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
5. #javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.
6. #javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.
The following legacy answer applies JSF version before 2.3
As of JSF 2.x there are 4 Bean Scopes:
#SessionScoped
#RequestScoped
#ApplicationScoped
#ViewScoped
Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates
if the web application invokes the invalidate method on the
HttpSession object, or if it times out.
RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back
to the client. If you place a managed bean into request scope, a new
instance is created with each request. It is worth considering request
scope if you are concerned about the cost of session scope storage.
ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all
requests and all sessions. You place managed beans into the
application scope if a single bean should be shared among all
instances of a web application. The bean is constructed when it is
first requested by any user of the application, and it stays alive
until the web application is removed from the application server.
ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF
specification uses the term view for a JSF page.) As soon as the user
navigates to a different page, the bean goes out of scope.
Choose the scope you based on your requirement.
Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54]
Is this a correct approach to inject #ApplicationScoped bean in #SessionScoped bean? will this lead my application scoped bean to be stored in the session of every user?
I have an application scoped bean that contains some values we share among all the system users, and now I need to get that values within a method in a session bean.
Injecting a bean of the same or a broader scope in another bean is completely legal and correct either in JSF or CDI beans, like the example you provided.
The difference between CDI beans and JSF managed beans regarding that is when you try to inject a bean of a narrower scope in another bean (e.g inject #RequestScoped bean into #SessionScoped one), which is only possible as long as you are using CDI #Named beans, while not possible when working with JSF #ManagedBean.
The reason why this is possible for CDI beans is related to their Proxy Pattern mechanism, which is more flexible compared with the JSF mechanism (based on invoking the setters in order to directly inject a physical instance).
This proxy mechanism, allow the CDI container to pass a reference to a proxy instead of the injected bean (unless a bean has the default scope #Dependent). Therfore, that proxy will be responsbale of handling all calls to the injected bean and forward / redirect them to the correct bean instance.
See also:
CDI: Contexts and Dependency Injection for the Java EE platform - Client proxies
Java EE 6 #javax.annotation.ManagedBean vs. #javax.inject.Named vs. #javax.faces.ManagedBean
Backing beans (#ManagedBean) or CDI Beans (#Named)?
ManagedProperty in CDI #Named bean returns null
I'm interested What is the proper way to use JSF pages with AJAX when I use CDI.
I tested to configure the CDI beans with #SessionScoped but I found that there is a problem with AJAX.
Is it proper to use AJAX with CDI beans configured with #ConversationScoped?
And I found that I have to put conversation.begin(); into the Bean constructor and conversation.end(); into Java method which must be when the session is completed. Can I somehow do this automatically?
P.S Can I use this code to automatically free the resource when the user closes the page?
#Remove
public void finishIt(){
conversation.end();
}
And I found that I have to put conversation.begin(); into the Bean constructor and conversation.end(); into Java method which must be when the session is completed.
That's correct. See also among others How to replace #ManagedBean / #ViewScope by CDI in JSF 2.0/2.1 for a concrete code example.
Can I somehow do this automatically?
If you want a bean which must live as long as you're postbacking on a single view, then upgrade to at least JSF 2.2. It provides a CDI compatible #ViewScoped out the box.
If you however want a bean which must live as long as you reference it in a view, regardless of the view you're sitting in, then consider using #ViewAccessScoped of DeltaSpike instead. Once you navigate to a view which doesn't reference the bean anywhere, it will be trashed.
See also:
How to choose the right bean scope?
By default the Conversation object is in transient state. Invocation of the begin method marks it as long-running (when a real conversation starts). Ending conversation (by invoking end method) marks Conversation object as transient.
A transient conversation scoped bean will live for a life cycle of single request .
long-ending conversation(initiated by conversation.begin) will run unless conversation.end is called.
Is it possible in JSF 2 to initialize a session-scoped managed bean as soon as the session context is loaded? I know it's possible with Application Scoped beans and the eager attribute in the #ManagedBean annotation, but does something similar exist for session beans? I have a session-scoped bean that I want to have loaded regardless of if a specific page is visited.
Are you sure you need a bean? If it is some general initialization stuff, you can use a HttpSessionListener, and on sessionCreated(..) initialize things.