0% found this document useful (0 votes)
16 views

03 Spring in Web Apps

Uploaded by

solar_740207221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

03 Spring in Web Apps

Uploaded by

solar_740207221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

2009 Marty Hall

Using g Spring p g in Web Applications


Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/spring.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

2009 Marty Hall

For live Java training, please see training courses at http //co rses coreser lets com/ Ser http://courses.coreservlets.com/. Servlets, lets JSP JSP, Str Struts, ts JSF, Ajax, GWT, Java 5, Java 6, Spring, Hibernate, JPA, and customized combinations of topics. p
Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial tutorial. Available at public venues, or customized versions can be held on-site at your Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. organization. Contact [email protected] for details. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Agenda
Servlet/JSP apps

4

Creating a Dynamic Web Project in Eclipse Adding Spring support Adding Spring JAR files and bean definition file Registering listeners in web.xml g bean definition file Loading Getting bean instances Creating a JSF Project in Eclipse Adding Spring support D fi i beans Defining b in i applicationContext.xml li ti C t t l Defining beans in faces-config.xml

JSF apps

2009 Marty Hall

Overview
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Why are Web Apps Different?


You need to access the bean definition file from many different places
With desktop Java apps, you can have a single piece of code that instantiates the container and gets beans
I.e., driver class that calls instantiates ClassPathXmlApplicationContext and calls getBean

With Web apps, each servlet wants access to beans


But you want to instantiate container once only

You need additional bean scopes


Standard Spring supports singleton and prototype Web apps also want request, session, and application

Note
We are not discussing the SpringMVC framework here, but rather how to use regular Spring beans in Web apps
6

Summary of New Approaches


Regular Web Apps
Put the two JAR files in WEB-INF/lib Put bean definitions in WEB-INB/applicationContext.xml
request and session scope now supported

Declare two listeners in web.xml


Container will be instantiated when app is loaded

Get container reference by using static method in WebApplicationContextUtils Get beans normally after that

JSF Apps
Same approach pp for JAR files, , bean defn file, , and listeners Declare variable-resolver in faces-config.xml Can declare beans in applicationContext or faces-config

2009 Marty Hall

Using Spring in Regular Java-Based Web Apps pp


Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Creating the App in Eclipse


Create Dynamic Web App
File New Project Web Dynamic Web Project
If you have made a Dynamic Web Project recently, you just do File New Dynamic y Web Project j can j

Add Spring support


R-click project, Spring Tools Add Spring Project Nature

Note
This tutorial t torial assumes ass mes that you o already alread know kno how ho to configure Eclipse for Tomcat (or another server) and are already familiar with servlets, JSP, and MVC
If not, see tutorials on Tomcat/Eclipse setup, servlets, JSP, and MVC at http://www.coreservlets.com/
9

Configuring the App for Spring: The Three Standard Files


Spring JAR files
Put spring.jar and commons-logging.jar in WebContent/WEB-INF/lib

Starting Starting-point point applicationContext.xml


Put empty p y file (with ( header and <beans..></beans> only) in WEB-INF
Unlike in desktop apps, the filename matters. The standard loading utility assumes that name and location

Non-Eclipse users
The structure of the Web app pp is not tied to Eclipse. p You still put JAR files in WEB-INF/lib and put applicationContext.xml in WEB-INF
10

Original Bean Definition File


Empty/Starting-point file
/WEB-INF/applicationContext.xml
If you want to change this default name/location, set a context p param called contextConfigLocation g to override it
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>

11

Configuring the App for Spring: Defining Listeners in web.xml web xml
ContextLoaderListener
This listener runs when the app is first started. It instantiates the ApplicationContext (from WEB-INF/applicationContext.xml) WEB INF/applicationContext.xml) and places a reference to it in the ServletContext You can retrieve this reference with the static getRequiredWebApplicationContext tR i dW bA li ti C t t method th d of f WebApplicationContextUtils

RequestContextListener
This listener is needed if you declare any of your beans to be request-scoped or session-scoped
I I.e., Web W b scopes instead i t d of f the th usual l Spring S i scopes of f singleton or prototype
12

Defining Listeners: web.xml


<?xml version="1.0" encoding="UTF-8"?> pp > <web-app <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> ste e c ass <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> </web-app>

13

2009 Marty Hall

Example Web App: Bank Balance Lookup p


Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Overview
Input form
Collects required user ID
Required

Collects preferred foreground and background colors


Optional

Results pages
Shows name and balance of customer with given ID Error if ID missing or unknown preferred colors Uses p
15

Overview (Continued)
Service interface
CustomerLookupService
Maps customer IDs to Customers

Service implementation
MapCustomerLookupService
Uses fixed HashMap of a few sample customers

applicationContext.xml
Defines preferred foreground and background colors
In session scope

Defines customer lookup service as a Map


In s singleton g eto scope

16

web.xml: Defining Listeners


<?xml version="1.0" encoding="UTF-8"?> pp > <web-app <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
Loads /WEB-INF/applicationContext.xml and puts reference to it in servlet context. Can be accessed with WebApplicationContextUtils.getRequiredWebApplicationContext

<listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener>


Lets you give request or session scopes to beans in applicationContext.xml. If you dont use these scopes, this listener is not required. But you should probably have this entry commented out in web.xml just in case you want those scopes later.
17

web.xml: Servlet Mappings


<servlet> <servlet-name>Input <servlet name>Input Form Servlet</servlet Servlet</servlet-name> name> <servlet-class>coreservlets.InputFormServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Input Form Servlet</servlet-name> <url-pattern>/input-form</url-pattern> </servlet-mapping> <servlet> <servlet-name>Customer Lookup Servlet</servlet-name> <servlet-class>coreservlets CustomerServlet</servlet-class> <servlet-class>coreservlets.CustomerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Customer Lookup p Servlet</servlet-name> <url-pattern>/get-customer</url-pattern> </servlet-mapping>
18

Color Preferences Bean


public class ColorPreferences implements Serializable { private String foreground, background; public String getForeground() { return(foreground); } public void setForeground(String foreground) { if (!isEmpty(foreground)) { this.foreground = foreground; } } // getBackground and setBackground private boolean isEmpty(String p p y( g value) ) { return((value == null) || (value.trim().equals(""))); }
19

In Web apps in general, session data should be Serializable. This is partly to support distributed apps, but the more important reason is that Tomcat and other servers will let session data live across server restarts if the data is Serializable.

Customer Lookup Service: Interface


public interface CustomerLookupService { public Customer getCustomer(String id); public Customer getRichestCustomer(); }

20

Customer Lookup Service: One Concrete Implementation


public class MapCustomerLookupService implements CustomerLookupService { private Map<String,Customer> sampleCustomers; public Map<String,Customer> getSampleCustomers() { return sampleCustomers; } public void setSampleCustomers(Map<String,Customer> sampleCustomers) { this.sampleCustomers = sampleCustomers; } public Customer getCustomer(String id) { if (id == null) { id = "unknown"; } return(sampleCustomers.get(id.toLowerCase())); } public Customer getRichestCustomer() { }
21

This will be set via <property name="sampleCustomers"> in applicationContext.xml

Customer Bean
public class Customer { private String customerID, customerID firstName, firstName lastName; private double balance; // Simple getters and setters public String getFormattedBalance() { return(String.format("$%,.2f", t (St i f t("$% 2f" getBalance())); tB l ())) } }

22

applicationContext.xml: Defining Color Preferences


<?xml version="1.0" encoding="UTF-8"?> p // p g g/ / <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="colorPreferences" class="coreservlets.ColorPreferences" scope="session"> p ope ty name="foreground" a e o eg ou d value="black"/> a ue b ac / <property <property name="background" value="#fdf5e6"/> </bean>

23

applicationContext.xml: Defining Lookup Service


<bean id="sampleLookupService" p p class="coreservlets.MapCustomerLookupService"> <property name="sampleCustomers"> <map> <entry key="a1234"> <bean class="coreservlets.Customer"> <property name="customerID" value="a1234"/> <property name="firstName" value="Rod"/> p ope ty name="lastName" a e astNa e value="Johnson"/> a ue Jo so / <property <property name="balance" value="123.45"/> </bean> </entry> </map> </property> </bean> </beans>
24

index.jsp
<% response.sendRedirect("input-form"); %>

25

Input Form (Servlet)


public class InputFormServlet extends HttpServlet { public void doGet(HttpServletRequest p ( p q request, q , HttpServletResponse response) throws ServletException, IOException { ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext( (getServletContext())); context.getBean("colorPreferences"); String St g add address ess = "/WEB-INF/jsp/input-form.jsp"; / N /jsp/ put o .jsp ; RequestDispatcher dispatcher = Since bean is already specified with request.getRequestDispatcher(address); session scope, there is no need to do session.setAttribute here. But it is still dispatcher.forward(request, response); necessary to call getBean. } }

26

Input Form (JSP)


<body bgcolor="${colorPreferences.background}" text="${colorPreferences text= ${colorPreferences.foreground} foreground}"> > <form action="get-customer" method="post"> <input type="text" name="cust-id"/> <input p type="password" yp p name="cust-password"/> p / <input type="text" name="fg" value="${colorPreferences.foreground}"/> <input type="text" name="bg" value="${colorPreferences.background}"/> <input type="submit" value="Show Balance"/> </form>

27

Input Form (Result)

28

Customer Lookup (Servlet)


public class CustomerServlet extends HttpServlet { public void doPost(HttpServletRequest p ( p q request, q , HttpServletResponse response) throws ServletException, IOException { ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext( (getServletContext())); CustomerLookupService lookupService = (Custo e oo upSe (CustomerLookupService)context.getBean("sampleLookupService"); ce)co te t.get ea ( sa p e oo upSe ce );

29

Customer Lookup (Servlet Continued) (Servlet,


String id = request.getParameter("cust-id"); String address; if (isEmpty(id)) { address = "missing-id.jsp"; } else { Customer customer = lookupService.getCustomer(id); if (customer == null) { request.setAttribute("id", q ( , id); ); address = "invalid-id.jsp"; } else { request.setAttribute("customer", customer); address = "show-customer.jsp"; } } address = "/WEB-INF/jsp/" + address;
30

Customer Lookup (Servlet Continued) (Servlet,


ColorPreferences colorPreferences = (ColorPreferences)context.getBean( colorPreferences ); (ColorPreferences)context.getBean("colorPreferences"); colorPreferences.setForeground(request.getParameter("fg")); colorPreferences.setBackground(request.getParameter("bg")); RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); } private boolean isEmpty(String value) { return((value == null) || (value.trim().equals(""))); } }

31

Customer Lookup (/WEB-INF/show-customer jsp) (/WEB-INF/show-customer.jsp)


<body bgcolor="${colorPreferences bgcolor= ${colorPreferences.background} background}" text="${colorPreferences.foreground}"> <table border="5" align="center"> <tr><th class class="title">Spring title >Spring Bank: Your Balance</th></tr> </table> <p/> <ul> <li>ID: ${customer.customerID}</li> <li>First name: ${customer.firstName}</li> <li>Last name: ${customer.lastName}</li> <li>Balance: ${customer.formattedBalance}</li> </ul>

32

Customer Lookup (/WEB-INF/invalid-id jsp) (/WEB-INF/invalid-id.jsp)


<body bgcolor="${colorPreferences bgcolor= ${colorPreferences.background} background}" text="${colorPreferences.foreground}"> <table border="5" align="center"> <tr><th class class="title">Spring title >Spring Bank: Error</th></tr> </table> <p/> <h1 class="error">No customer with ID '${id}'.</h1> ${ } / </body></html>

33

Customer Lookup (/WEB-INF/missing-id jsp) (/WEB-INF/missing-id.jsp)


<body bgcolor="${colorPreferences bgcolor= ${colorPreferences.background} background}" text="${colorPreferences.foreground}"> <table border="5" align="center"> <tr><th class class="title">Spring title >Spring Bank: Error</th></tr> </table> <p/> <h1 class="error">Missing g customer ID.</h1> / </body></html>

34

Customer Lookup (Results: Good Data)

35

Customer Lookup (Results: Bad Data)

36

2009 Marty Hall

Using Spring in pp JSF Apps


Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Creating the App in Eclipse


Create Dynamic Web App
File New Project Web Dynamic Web Project

Add Spring support


R-click, R li k Spring S i Tools T l Add Spring S i P Project j N Nature

Add JSF Support


R-click R click project, project Properties, Properties Project Facets, Facets JSF
You can also choose JSF under the configuration tab when first creating dynamic Web project You Y can use JAR fil files f from E Eclipse li or get t your own ( (e.g., from myfaces.apache.org). I get my own.

Note
This section assumes that you already know JSF
If not, see http://www.coreservlets.com/JSF-Tutorial/
38

Configuring the App for Spring and JSF: The Standard Files
Spring JAR files
Put spring.jar and commons-logging.jar in WebContent/WEB-INF/lib

Starting Starting-point point applicationContext.xml


Put empty p y file (with ( header and <beans..></beans> only) in WEB-INF

Starting-point faces-config.xml
Empty file with start/end tags only. Eclipse creates this automatically.

Note
39

First two bullets are exactly the same as in previous section on using Spring in regular Web apps

Configuring the App for Spring and JSF: web web.xml xml Settings
Two Spring listeners
ContextLoaderListener and RequestContextListener
Same as in previous section on regular Web apps

Standard JSF settings


At very least, FacesServlet mapped to some url-pattern like *.faces

40

web.xml Settings
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener / ste e c ass </listener-class> </listener> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping>

41

Configuring JSF to Recognize Spring Beans: Idea


Not good to call getBean
It would be technically legal to get the ApplicationContext and call getBean explicitly (probably from the backing bean beans s action controller method). But this is a bad idea since JSF is geared around declaring beans in config files only.

JSF already l d supports t dependency d d injection i j ti


The managed-property element lets you insert other beans inside newly created ones.
The only trick is to be able to refer to Spring beans

Use DelegatingVariableResolver
Declare in faces-config.xml. Now, whenever JSF sees a bean name, it uses JSF rules first, then Spring rules next.
42

Configuring JSF to Recognize Spring Beans: faces-config faces-config.xml xml


<faces-config> <application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver> </application> </faces-config>

43

2009 Marty Hall

Beans in Two Config Files


Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

JSF/Spring Example 1:

Overview
Functionality and appearance
Exactly the same as in previous app
Given customer id, shows name and balance (or error)

Approach
applicationContext.xml
Exactly y the same as in previous example
Defines session-scoped ColorPreferences and singleton-scoped CustomerLookupService

faces-config.xml g
Similar approach to standard JSF apps
Defines backing bean Defines navigation g rules

Access Spring beans with managed-property


Backing bean gets Spring beans as properties
45

Files not Shown


Java classes unchanged from last example
ColorPreferences
Bean with foreground, background

Customer
Bean with customerID, firstName, lastName, balance

CustomerLookupService
Interface with getCustomer method

MapCustomerLookupService
Implementation with HashMap of some sample customers

web.xml
Unchanged from version shown in previous section on general JSF configuration
Two Spring listeners, servlet mapping for FacesServlet
46

applicationContext.xml
Unchanged from previous example
Defines session-scoped ColorPreferences
<bean id="colorPreferences" class="coreservlets.ColorPreferences" scope session scope="session"> <property name="foreground" value="black"/> <property name="background" value="#fdf5e6"/> </bean>

Defines singleton-scoped CustomerLookupService


<bean id="sampleLookupService" class="coreservlets.MapCustomerLookupService"> <property name="sampleCustomers"> p p <map></map> </property> </bean>
47

Backing Bean: Properties


public class CustomerBackingBean { by JSF when form submitted. private String inputID, password; Filled in by action controller method (shown on next slide). private Customer customer; private ColorPreferences colorPreferences; private CustomerLookupService lookupService;
Corresponding setters called

// Getters and setters // for above 5 properties

Setter methods called when bean created because of managed-bean-property managed bean property in faces-config.xml. The incoming values are Spring beans.

48

Backing Bean: Action Controller Method


public String getBalance() { if (isEmpty(inputID)) { return("missing-id"); } else { customer = lookupService.getCustomer(inputID); if (customer == null) { return("invalid-id"); } else { return( show-balance ); return("show-balance"); } } }

49

faces-config: Variable Resolver


<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE > > <faces-config> <application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver> / </application>

50

faces-config: Backing Bean


<managed-bean> <managed-bean-name>formBean</managed-bean-name> <managed-bean-class> coreservlets.CustomerBackingBean </managed bean class> </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>lookupService</property-name> p p y p /p p y <value>#{sampleLookupService}</value> </managed-property> <managed-property> <property-name>colorPreferences</property-name> Gets the Spring bean called sampleLookupService <value>#{colorPreferences}</value> and passes it to the setLookupService method of the JSF backing bean called formBean (i.e., injects it </managed-property> into the lookupService property). </managed-bean>
Gets the Spring bean called colorPreferences and injects it into the colorPreferences property of the backing bean. 51

faces-config: Navigation Rules


<navigation-rule> <from-view-id>/welcome jsp</from-view-id> <from-view-id>/welcome.jsp</from-view-id> <navigation-case> <from-outcome>show-balance</from-outcome> <to view id>/show customer.jsp</to view id> <to-view-id>/show-customer.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>missing-id</from-outcome> g / <to-view-id>/missing-id.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>invalid-id</from-outcome> <to-view-id>/invalid-id.jsp</to-view-id> </navigation-case> </navigation-rule>
52

index.jsp
<% response.sendRedirect("welcome.faces"); %>

53

Input Form (welcome.jsp)


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> <body bgcolor="<h:outputText value="#{formBean.colorPreferences.background}"/>" te t text="<h:outputText :output e t value="#{formBean.colorPreferences.foreground}"/>"> <h:form> <h:inputText value="#{formBean.inputID}"/> <h:inputSecret value="#{formBean.password}"/> <h:inputText value="#{formBean.colorPreferences.foreground}"/> <h:inputText value="#{formBean.colorPreferences.background}"/> <h:commandButton action="#{formBean.getBalance}"/> </h:form>

54

Main Results Page (show-customer jsp) (show-customer.jsp)


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> <body bgcolor="<h:outputText value="#{formBean.colorPreferences.background}"/>" te t text="<h:outputText :output e t value="#{formBean.colorPreferences.foreground}"/>"> <ul> <li>ID: <h:outputText value="#{formBean value= #{formBean.customer.customerID} customer customerID}"/> /> </li> <li>First name: <h:outputText value="#{formBean.customer.firstName}"/> </li> <li>Last name: <h:outputText value="#{formBean.customer.lastName}"/> </li> <li>Balance: i <h:outputText value="#{formBean.customer.formattedBalance}"/> </li> </ul>

55

Error Page 1 (invalid-id jsp) (invalid-id.jsp)


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> g uri="http://java.sun.com/jsf/html" p //j /j / p prefix="h" %> <%@ taglib <f:view> <body bgcolor="<h:outputText value="#{formBean.colorPreferences.background}"/>" text="<h:outputText value="#{formBean.colorPreferences.foreground}"/>"> c ass e o <h1 class="error"> No customer with ID '<h:outputText value="#{formBean.inputID}"/>'. </h1>

56

Error Page 1 (missing-id jsp) (missing-id.jsp)


<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> g uri="http://java.sun.com/jsf/html" p //j /j / p prefix="h" %> <%@ taglib <f:view> <body bgcolor="<h:outputText value="#{formBean.colorPreferences.background}"/>" text="<h:outputText value="#{formBean.colorPreferences.foreground}"/>"> class="error">Missing ass e o ss g custo customer e ID.</h1> . / <h1 c

57

Results: Good Data (Same as Previous Example)

58

Results: Bad Data (Same as Previous Example)

59

2009 Marty Hall

JSF/Spring Example 2:
Beans in One Config File
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Overview
Issue with previous example
Beans defined in two different files
Some using Spring syntax, some using JSF syntax

Approach
applicationContext.xml
Defines the Spring g beans as before
Defines session-scoped ColorPreferences and singleton-scoped CustomerLookupService

Also defines the backing bean

faces-config.xml
Defines navigation rules (and variable resolver) only

Functionality and appearance


Exactly the same as in previous two apps
61

Changes from Previous Example


faces-config.xml
Deleted the entire <managed-bean> entry

applicationContext.xml
Added Add d the h f following ll i simpler i l entry
<bean id="formBean" g class="coreservlets.CustomerBackingBean" scope="request"> <property name="lookupService" ref="sampleLookupService"/> property name name="colorPreferences" colorPreferences ref ref="colorPreferences"/> colorPreferences / <property </bean>

Two advantages
S Spring i d dependency d i injection j ti syntax t i is simpler i l and d more powerful All bean definitions in the same file

62

2009 Marty Hall

Wrap-up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Summary: Regular Web Apps


Two JAR files
Put Spring JAR files in WEB-INF/lib

Bean definition file


Put P applicationContext.xml li i C l in i WEB-INF WEB INF
Scopes now include request and session in addition to singleton and prototype

Listeners
Two listener definitions in web.xml

Getting G tti beans b


Access ApplicationContext with static getRequiredWebApplicationContext method of WebApplicationContextUtils Call getBean normally

64

Summary: JSF-Based Apps


Basic setup
Start with same setup as regular Web apps Use normal JSF definition of FacesServlet in web.xml

faces-config.xml faces config xml


Declare DelegatingVariableResolver

Option 1
Declare Spring beans in applicationContext.xml g beans in faces-config.xml g Declare backing
Refer to Spring beans with managed-bean-property

Option 2
Declare all beans in applicationContext.xml
Refer to other beans with ref and normal Spring syntax
65

2009 Marty Hall

Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

You might also like