Using Spring with JSF: the managed bean tutorial
title: 'Using Spring with JSF: the managed bean tutorial'
date: 2009-03-06T00:06:49+00:00
author: Marco Molteni
layout: post
permalink: /spring-jsf-tutorial
main-class: java
categories: Spring
color: '#7AAB13'
title: "Using Spring with JSF: The Managed Bean Tutorial"
date: 2009-03-06T00:06:49+00:00
author: Marco Molteni
layout: post
permalink: /spring-jsf-tutorial
main-class: java
categories: Spring
color: '#7AAB13'
Using Spring with JSF: The Managed Bean Tutorial
Two J2EE technologies are becoming dominant in the Java environment: Spring and JavaServer Faces (JSF).
Spring beans can be easily integrated into a JSF project. They can coexist with JSF managed beans or interact directly with the view.
Steps to Use Spring in a JSF Project
1. Add Required Libraries
Ensure that Spring libraries are accessible in your project.
2. Configure web.xml
Declare the Spring listener in web.xml
:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
To use request values between the view (JSP/JSF) and the bean, add a second listener:
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
3. Configure faces-config.xml
Typically, faces-config.xml
defines the managed beans. To enable the use of Spring beans, add the following lines:
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
4. Define Beans in applicationContext.xml
Declare your beans in applicationContext.xml
like a standard Spring application, with an important difference: the scope property.
<bean name="personMB" class="ch.genidea.ofac.web.jsf.Person" scope="request">
<property name= ... />
</bean>
By default, the scope property is set to singleton
. In a web application, you have three options:
- request: The bean exists for the lifecycle of a single HTTP request.
- session: The bean is tied to an HTTP session.
- global session: Typically used in a portlet context.
5. Use the Bean in a JSP Page
You can now call the bean directly in your JSP/JSF page:
<h:outputText value="First name" />
<h:inputText value="#{personMB.firstName}" id="personName" />
<h:outputText value="Family name" />
<h:inputText value="#{personMB.lastName}" id="personFamilyName" />
By following these steps, you can successfully integrate Spring beans into your JSF application, enhancing modularity and maintainability.