Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Build Apache Geronimo applications using JavaServer Faces, Part 5: Integrating your JSF application with Spring

Chris Herborth, Freelance, Freelance Writer
Photo of Chris Herborth
Chris Herborth is an award-winning senior technical writer with more than 10 years of experience writing about operating systems and programming. When he's not playing with his son Alex or hanging out with his wife Lynette, Chris spends his spare time designing, writing, and researching (that is, playing) video games.

Summary:  This final installment wraps up the five-part tutorial series by introducing you to the Spring Framework. Learn to integrate your Java™Server Faces (JSF) applications with Spring, a popular framework that makes it easier for Apache Geronimo developers to build Java Platform, Enterprise Edition (Java EE) applications. You'll use Spring to continue developing the front end for the example Developer Forum Signup application.

View more content in this series

Date:  19 Dec 2006
Level:  Intermediate PDF:  A4 and Letter (325 KB | 28 pages)Get Adobe® Reader®

Activity:  11929 views
Comments:  

Adding Spring MVC to devSignup

You now have devSignup ready to add in Spring MVC functionality, so let's jump right in.

Get started

  1. Right-click the devSignup project in Eclipse's Navigator view, then choose Properties from the context menu. Eclipse displays the Properties dialog box.
  2. Click JSF Library References in the list to display the JSF Library References panel (see Figure 3).

Figure 3. Adding Spring to the devSignup project
Adding Spring to the devSignup project
  1. Click the New button in the pick-list area (that is, not the one beside the Implementation Library drop-down list) to display the Create JSF Library dialog box. You use this dialog to define a JSF component library, which you can then include in your project. This is handy for adding component libraries that include several JAR files, or that depend on additional JAR files from other projects.
  2. Enter a library name (I'm going to use Spring Framework) in the Library Name field, then choose v1_1 from the Version Supported drop-down menu, since MyFaces implements JSF 1.1.
  3. Click the Add button, then choose the Spring .jar file: spring.jar (see Figure 4).

Figure 4. Making the Spring Framework library reference
Making the Spring Framework library reference

Yes, that's it. The Spring Framework also ships with various other JAR files; the spring.jar contains everything found in these. If you're after finer-grained control of your application's contents or you're pressed for space on the server, you can pick and choose from these. Refer to the readme.txt file that comes with the Spring distribution for a complete listing of each JAR file's dependencies. There's one more file (spring-mock.jar), which includes mock server contexts and other classes that make unit testing a breeze:

  • spring-core.jar -- Core utilities; everything requires this
  • spring-beans.jar -- JavaBeans support, bean container
  • spring-aop.jar -- AOP framework, source-level metadata support, AOP Alliance interfaces
  • spring-context.jar -- Application context, validation, Java Naming and Directory Interface (JNDI), UI context support
  • spring-dao.jar -- Data Access Objects (DAO) support, transaction infrastructure
  • spring-jdbc.jar -- JDBC support
  • spring-support.jar -- Java Management Extensions (JMX) support, J2EE Connector Architecture (JCA) support, scheduling support, mail support, caching support
  • spring-web.jar -- Web application context, multipart resolver, Struts support, JSF support, Web utilities
  • spring-webmvc.jar -- Framework servlets, Web MVC framework, Web controllers, Web views
  • spring-remoting.jar -- Remoting support, Enterprise JavaBeans (EJB) support, Java Message Service (JMS) support
  • spring-orm.jar -- iBATIS SQL Maps support, Apache Object Relational Bridge (OJB) support, TopLink support, JDO support
  • spring-hibernate.jar -- Hibernate 2.1 support, Hibernate 3.0 and later support

  1. Click Finish (shown in Figure 4) to add the new Spring Framework library to the list in the JSF Library References panel of the project Properties. The new Spring Framework library is added to the list on the right, which will be automatically included with your project's .war file.
  2. Click OK to apply your changes and close the project Properties dialog box.

Your task list

To enable the Spring Framework, you need to add a few things to your application:

  • A new <listener> in web.xml
  • A new <variable-resolver> in faces-config.xml
  • A new managed property to your bean; this is how you inject a Spring bean into the existing application
  • An applicationContext.xml file that defines the application's beans (including the existing JSF bean)
  • A new property for the SignupData bean
  • A new Spring-based bean
  • Something to show that the new Spring bean is doing something

Lets get to work!


Add <listener>

  1. Add the code from Listing 6 to web.xml before the existing <listener> element as a child of the <web-app> element, not any of the other web.xml tags.

Listing 6. Enabling the Spring Framework in web.xml
                    
<listener>
    
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

The <listener> element adds Spring's ContextLoaderListener to the application; it starts up Spring's root WebApplicationContext, which handles creating and configuring the other parts of Spring that are needed while booting the application.


Add the Spring variable resolver

  1. Save your web.xml file, and right-click the faces-config.xml file.
  2. Choose Open With > XML Editor from the context menu so you can tell your application to use one of the Spring variable resolvers.
  3. Add the lines from Listing 7 to faces-config.xml in the <application> element.

Listing 7. Telling faces-config.xml to use the Spring variable resolver
                    
<variable-resolver>org.springframework.web.jsf.DelegatingVariableResolv
er</variable-resolver>

The DelegatingVariableResolver will perform lookups for any bean name or bean property references made by the application. If it can't resolve a reference to a Spring bean or property, it delegates the lookup to the standard JSF variable resolver.


Add a new managed property to your bean

You're going to add a new property to the signupData bean declared in this file; the hash property is going to be managed by a Spring bean to demonstrate the technique of injecting Spring into an existing application.

  1. Add the lines from Listing 8 to faces-config.xml inside of the <managed-bean> block that defines the signupData bean.

Listing 8. Adding a managed property to your existing bean
                    
<managed-property>
    <property-name>hash</property-name>
    <value>#{genHash.hash}</value>
</managed-property>

This creates the new hash-managed property, which maps to the hash property of the new genHash bean you're going to define shortly.


Add the applicationContext.xml file

  1. Save your faces-config.xml file.
  2. Right-click the WEB-INF folder in your devSignup project, then choose New > File from the context menu.
  3. Enter applicationContext.xml as the file's name, then add the lines from Listing 9 to the new file.

Listing 9. Defining the beans managed by Spring
                    
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="signupData" class="devSignup.SignupData" 
lazy-init="true"/>
    <bean id="genHash" class="devSignup.HashGenerator" 
lazy-init="true"/>
</beans>

These are the beans that Spring will know about, which is why you'll find your JSF bean, signupData, here as well. These will be created and managed by Spring's bean factory as necessary. If you'd left the lazy-init attribute as the default (false), the beans would be created as soon as the application starts. With lazy-init set to true, the beans are created when they're needed.


Your Spring-based bean

  1. Add the Java code from Listing 10 to the SignupData.java in the devSignup folder; this adds the hash property and its accessors.

Because this is a managed property referring to a property found in another bean, Spring uses it internally to refer to that other bean's property. It won't actually be used by the JSF application, because Spring's DelegatingVariableResolver intercepts any references to it.


Listing 10. Adding the hash property to SignupData.java
                    
private String _hash = null;

public SignupData() {
    this._birthday = new java.util.Date();
}

public String getHash() {
    return this._hash;
}

public void setHash( String newHash ) {
   this._hash = newHash;
}

You also need to create a new Java class, HashGenerator, in the devSignup package.

  1. Right-click the src folder in the devSignup project, then choose New > Other from the context menu.
  2. In the wizard, choose Class, then click Next to create a new Java class.
  3. Set the package to devSignup (or click the Browse button beside the Package field and choose devSignup) and the name to HashGenerator.
  4. Click Finish to create the new class, and edit its source to include the code from Listing 11.

Listing 11. The new HashGenerator class
                    
package devSignup;

import javax.faces.context.FacesContext;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

public class HashGenerator {
    public void setHash( String newHash ) {
        // Do nothing, this is a read-only bean.
        return;
    }
    
    public String getHash() {
        ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(
                FacesContext.getCurrentInstance());

        try {
            SignupData myBean = (SignupData)ctx.getBean("signupData" );

            return Integer.toString( myBean.getScreenName().hashCode() );
        } catch( NoSuchBeanDefinitionException ex ) {
            return "no-data-bean";
        } catch( javax.faces.FacesException ex ) {
            return "no-screen-name";
        }
    }
}

This HashGenerator bean has one read-only property: hash. Attempting to set this property has no effect; another option is to log this or maybe use it to seed a more powerful hash-generation method. It also features the first Spring Java code you've seen, in the getHash() method.

In the getHash() method, you use Spring's FacesContextUtils.getWebApplicationContext() method to create an ApplicationContext object, which you can then use to look up specific bean instances running in the application. Here you use it to find the signupData bean so you can feed its screenName property through the Java String object's hashCode() method. You handle exceptions that might be raised if the bean can't be found or if you've requested an invalid property.

That's all there is to it. Now, when you build and deploy the application, the beans will be running inside of Spring, along with all of the other goodies that Spring provides. A more complex application could take advantage of them quite easily; for example, you could use Spring's support for Hibernate (an object/relational persistence and query service) to store and retrieve user data and add a way for existing users to log in to the hypothetical developer forums.


Your new Spring-based bean in action

One last thing you should do is add something to the application so you can see this new HashGenerator bean in action.

  1. Open the signup-success.jsp file in Eclipse. As you'll recall, this is the page that gets displayed when someone successfully makes it through the signup page. You'll change the contents of the <p> element so it'll display the user's new screen name, and their calculated hash value.
  2. Replace the current <p>...</p> element with the contents of Listing 12.

Listing 12. Showing the fruits of your labor
                    
<p>
Your application was successful, ${signupData.screenName}, welcome to our 
forums!
Your hash is ${signupData.hash}.
</p>

Now instead of a generic welcome message, they'll be welcomed by name and see the name coming directly from the signupData bean and the hash coming from the HashGenerator bean referenced by signupData's hash property. It looks something like Figure 5.


Figure 5. Success, now with a more personalized message
Success, now with a more personalized message

Since you're finished changing the Developer Forum Signup application, you need to deploy it on Geronimo.


Deploy the new Developer Signup application

Now is a good time to see how things are working out with your Developer Signup application. You need to build the project, export a WAR file, and deploy it to the Geronimo server.

  1. Click your devSignup project in Eclipse's Navigator view, then choose Project > Build Project from the menu. Eclipse compiles your Java code and validates your JSP pages and XML files.
  2. Right-click devSignup in the Navigator view, then choose Export from the context menu.
  3. In the Export wizard, expand the Web group, choose WAR file, then click Next to display the WAR Export panel (as shown in Figure 6).

Figure 6. Exporting a WAR file
Exporting a WAR file
  1. Click the Browse button to select a destination directory and file name for your .war file. (I'm saving mine to my desktop as devSignup.war so I can easily find it when I go to deploy it on the server.)
  2. Click Finish to export the .war file.
  3. Fire up your favorite Web browser, and access http://localhost:8080/console/ (substitute your Geronimo server's host name for localhost if it's not running on the same machine). This will display the Geronimo management console login screen.
  4. Log in (remember that the default user name is server and the default password is manager, and you should change these) to access the administration console.
  5. If you've already got devSignup running on your server because you followed along with the previous tutorials, click the Web App WARs entry in the Applications section of the list on the left-hand side of the screen. This will give you a list of all installed Web applications, each with a handy Uninstall link. Uninstall devSignup before attempting to deploy a new version.
  6. Click Deploy New from the Applications section in the Console Navigation list to display the Install New Applications screen.
  7. Click the Browse button next to the Archive field, and browse to your recently-created .war file.
  8. Since Start app after install is already checked, click Install to upload the .war file and launch your application. You'll see a success message after your browser finishes uploading the archive and Geronimo finishes launching your application.

That's it, you've successfully extend the Developer Signup Web application using the powerful Spring Framework!

4 of 8 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Java technology, WebSphere
ArticleID=171457
TutorialTitle=Build Apache Geronimo applications using JavaServer Faces, Part 5: Integrating your JSF application with Spring
publish-date=12192006
author1-email=chrish@pobox.com
author1-email-cc=troy@backstopmedia.com