Saturday, April 4, 2009

Creating startup Listener in JSF

Here I will show how to create a start-up listener while developing in JSF based application.

There are basically 4 steps in doing this:
- Step 1: Defining in web.xml
- Step 2: Creating the listener class
- Step 3: Creating the managed bean
- Step 4: Creating page


Step 1:
First we define the startup listener in our web.xml file as follows:




Step 2:

As defined in web.xml file, we will create our listener class under the com.ns.util package and name it as WebStartupListener. See this screenshot:




This class does the followings:
- It extends org.springframework.web.context.ContextLoaderListener and implement javax.servlet.ServletContextListener

- It should implement the business logic in contextInitialized method, which is an abstract method of the ServletContextListener class

- From the contextInitialized method, we just call our private method populateApplicationContext. We simply get the list of countries by calling a getAllCountriesInList() method (just a dummy method); populate an ArrayList of SelectItem objects; and finally put the populated list into the applicationContext by calling this method. (Please note Line 1). Since the application context is now set with the attribute value "LIST_OF_COUNTRIES", whenever we need this list of populated countries in our page, we just invoke this attribute value. I will show this next.

- The applicationContext should be destroyed within the contextDestroyed method, another abstract method of ervletContextListener

Our CountryVO POJO would be something like this:




Step 3:
Next we define the managed bean class, which we will be suing for capturing the selected item (CountryVO object) from the drop down in our page. The name of our managed bean class is UserBeanAction. Screenshot below:




- In this class, we have taken an instance of the CountryVO object, to set and get values of the CountryVO class by its primary key in the web page

- And an instance of the HtmlSelectOneMenu object, to bind CountryVO object with the dropdown list in page



Step 4:
Finally, the logic in our web page:




Note this line:



This is just the value we populated in our WebStartupListener class, and now we are simply using it in our page with the JSF el syntax.

Pretty simple, isn't it?