03 Spring in Web Apps
03 Spring in Web Apps
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
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.
Note
We are not discussing the SpringMVC framework here, but rather how to use regular Spring beans in Web apps
6
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
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
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
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
13
Overview
Input form
Collects required user ID
Required
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
16
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.
20
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
23
index.jsp
<% response.sendRedirect("input-form"); %>
25
26
27
28
29
31
32
33
34
35
36
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-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
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
Use DelegatingVariableResolver
Declare in faces-config.xml. Now, whenever JSF sees a bean name, it uses JSF rules first, then Spring rules next.
42
43
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
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>
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
49
50
index.jsp
<% response.sendRedirect("welcome.faces"); %>
53
54
55
56
57
58
59
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
faces-config.xml
Defines navigation rules (and variable resolver) only
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
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.
Listeners
Two listener definitions in web.xml
64
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
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.