JSF Mini Book – Tips, concepts and good practices

Avoiding @SessionScoped type. Check all Scope Types

Several tutorials found in the internet use the @SessionScoped type to make easier to understand. The @SessionScoped it is easy and practical to use but it allocates the data in the server memory. To each object/list put in a Session ManagedBean a new piece of the server memory will be allocated.

To build a good JSF application it is required to understand how each ManagedBean scope works. Let us see below the definition of each scope:

  • @RequestScoped – works like a HTTP “get/post” where the received data will be handled and a response will be sent to the client; once the response is sent to the client all request data will be deleted of the server memory. This scope has an easy behavior to understand; the problem of this approach is that the developer has to write in the page all data that will be sent to the JSF create the object to be used in the ManagedBean. Imagine a JSF datatable with all recorded users of the system with a “see detail” button; it would be required to put the user id hidden in the page to send it to the ManagedBean find the user in the database. This scope is “thread-safe” and can be used with CDI (Contexts and Dependence Injection). The RequestScoped will release the used memory when it finishes handling a user request (to see how to do a datatable with RequesScoped click here).
  • @ApplicationScoped – a ManagedBean defined as @ApplicationScoped will always be available to all application users request/response. This kind of scope is ideal do hold cached data like: combos, lists and configuration objects. This scope is not “thread-safe” and can be used with CDI. If any information of a @ApplicationScoped ManagedBean is required before the user access any page, just edit the @ManagedBean annotation: “@ManagedBean(eager=true)”. The eager attribute will notify the container to initialize the ManagedBean before any request to this class.
  • @SessionScoped – keep all objects/attributes/lists of the ManagedBean in the container memory. If the number of users increases the amount of memory in the server allocated will increase too.To each HTTP session created a new ManagedBean will be allocated in the memory with all its objects; it behaves just like the HttpSession. Pay attention to this: A ManagedBean is not “thread-safe” and can be used with CDI. Imagine that a user open a tab X and starts a request, but the request is taking too long so the user will open other tab (let us name it Y) and do the same request again; after the user receives the result of the request in the tab Y, he will update an object and will persist it. If the user returns to the tab X he will have the objects will old values and this old values may provoke the ManagedBean to behave in an unexpected way.
  • @ViewScoped – this scope is considered to be between the RequestScoped and the SessionScoped. The data in this type of ManagedBean will stay alive while the user stills in the page. When the user leaves the page all the data contained in the ManagedBean will be deleted of the server memory; the server will have the memory free again to work with. This scope type is ideal do work with Ajax requests. Every time a “pop up/dialog” is displayed the data inside the ManagedBean could be used. It is “thread-safe” but it is not compatible with CDI (to see more of this approach click here).
  • @ConversationScoped – this type of ManagedBean is exclusive to CDI applications and is “thread-safe”. It behaves like @ViewScoped but what makes it different is that: the end of the conversation with the user request is programmatically, in other words, the developer must begin and finish the state of the ManagedBean. Just after the command to finish the state of the ManagedBean is that the objects/list/attributes will be released. To use the ConversationScoped the following steps must be taken:
    • Create a file named “beans.xml” inside the “src/META-INF/”
    • Use the annotation “javax.enterprise.context.ConversationScoped”
    • Inject an object of the javax.enterprise.context.Conversation type
    • Invoke the methods conversation.begin() and conversation.end() to start and to end the ManagedBean state. Notice that the process is just like a database connection; we must be sure that we start and that ,at some point, it will end. The code below show how to do it:
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;

@Named()
@ConversationScoped
public class CarMB {

	@Inject
	private Conversation conversation;

	private enum Status {
		BEGIN, END, NOTHING
	};

	private Status conversationStatus;

	public void useCar(String command) {

		if (conversationStatus.equals(Status.BEGIN)) {
			conversation.begin();
		}

		// work with data

		if (conversationStatus.equals(Status.END)) {
			conversation.end();
		}
	}

	// other methods
}

A question that might come to the developer mind is: “If a user clicks several times in a button, when using Ajax, the ManagedBean still thread-safe?”

The answer is yes. In the JSF specification (13.3.2) says that all Ajax requests must be put in a queue before been sent to the container. A request is sent and just when it finishes the next request will be sent.

18 thoughts on “JSF Mini Book – Tips, concepts and good practices

  1. Really cool material! I agree with Tim. If this could be distributed in pdf format, you will become a little more famous. :) Thanks, good job!

  2. I’m not able to see this library applied in my program.
    Output is: Real Madrid, Champion!!! (No image and style)

    Please let me know what I’m missing.

  3. I was trying to learn Spring MVC for last 2 months, Every time i try to start, i get stuck somewhere. 2 Months passed, and i did not learn anything. I purchased two books for spring. Finally i quit Java web programming. One day I thought to give a try to JSF. and found some tutorials online, worked on them and I loved it. Your tutorials are going to help me a lot.
    Thank you so much.
    I would like to tell people here, don’t go near spring, It’s a piece of crap.

    • Arslan,

      Thanks for the feedback.

      My next post will be a full web application with Spring MVC.

      Maybe this application will help you understanding better the Spring, it is a good tool! =D

      See you later.

  4. With your code lines

    and

    eclipse was giving error that:

    Multiple annotations found at this line:
    – Invalid location of text (“) in tag ().
    – Invalid location of text (=”) in tag ().
    – Element type “h:outputStylesheetlibrary” must be followed by either attribute specifications, “>”
    or “/>”.

    So I’ve corrected it by changing lines to

    But I think as you mentioned in case of versions of resources, it will automatically picks up latest version. but the code I’m using will not control the version. It looks like hard-coded.

    What you say about it?

    Moreover, You wrote:
    “To use a mapped library by the ResourceHandler let us create a folder named “index.xhtml” inside the folder “/WebContent”.”

    I think you have not created a folder name “index.xhtml” but you have created a file named “index.xhtml”. If I’m right then you need to correct it. :)

    • Hello Arslan, how are you?

      Unfortunately the xml are not displayed here. =/

      Could you send me an email with the code and the texts that you wrote?

      Thanks for your support and passing by.

      My email is contato (at] uaihebert (d0T) com

      Thanks

Leave a Comment