jsf2 using spring

Upload: chethan-ramaiah

Post on 05-Apr-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 JSF2 Using Spring

    1/24

    2010 Marty Hall

    Using Spring with JSF 2.0

    Originals of Slides and Source Code for Examples:

    -

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    . .

    2010 Marty Hall

    For live training on JSF 1.x or 2.0, please seecourses a p: courses.coreserv e s.com .Taught by the author ofCore Servlets and JSP, More

    , .venues, or customized versions can be held on-site at

    your organization.

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    ourses eve ope an aug y ar y a Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x& 2.0, Ajax, GWT, custom mix of topics

    Ajax courses can concentrate on 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) or survey several

    Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate/JPA, EJB3, Ruby/Rails, SOAP-based and RESTful Web Services

    Contact [email protected] for details

  • 7/31/2019 JSF2 Using Spring

    2/24

    Topics in This Section

    Fast review of Spring dependency injection

    Configuring a JSF/Spring project in Eclipse

    Defining beans in two places JSF backing beans in faces-config.xml

    Spring beans in applicationContext.xml

    All beans in applicationContext.xml

    5

    2010 Marty Hall

    Overview

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 7/31/2019 JSF2 Using Spring

    3/24

  • 7/31/2019 JSF2 Using Spring

    4/24

    You are Using Spring Already:

    IssueNormal Spring already supports ways to access beans.

    So why add a new way for JSF?

    You need to access bean definitions from many places With deskto Java a s ou can have a sin le iece of

    code that instantiates the container and gets beans

    I.e., driver class that instantiates ClassPathXmlApplicationContextand calls getBean

    With JSF apps, each controller wants access to beans

    But you want to instantiate container once only

    Standard Spring supports singleton and prototype

    JSF apps also want request, session, and application9

    2010 Marty Hall

    JSF Apps

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 7/31/2019 JSF2 Using Spring

    5/24

    Creating the App in Eclipse

    Make a JSF 2.0 app in the normal manner e ew ro ect e ynam c e ro ect

    Then copy jsf-api.jar, jsf-impl.jar, blank faces-config.xml,and the web.xml settings. Recommended: JSTL JAR files.

    r, copy rename s - an pro ecBoth options described in Getting Started section

    Add the same 3 files S rin usuall uses spring.jar and commons-logging.jar

    Put these in WEB-INF/lib along with JSF JAR files

    . Put this in WEB-INF

    If you are using Spring IDE Eclipse pluginR-click project, Spring Tools, Add Spring Project Nature

    Adds smart support for editing applicationContext.xml11

    Eclipse Project Layout

    Needed in all JSF apps. Can be downloaded from

    https://javaserverfaces.dev.java.net/download.html

    Needed in JSF apps that use ui:repeat. Can be downloaded from

    https://jstl.dev.java.net/download.html

    Needed in all Spring apps. Can be downloaded from

    htt ://www.s rin source.or /download

    (Reminder: you can download this entire Eclipse project, with all files

    already included, at coreservlets.com)

    Empty to start with, but see later slides.

    12

    Contains only standard JSF declarations to start with,

    but see later slides.

  • 7/31/2019 JSF2 Using Spring

    6/24

    Original Bean Definition File

    /WEB-INF/applicationContext.xml you wan o c ange s e au name oca on, se a

    context param called contextConfigLocation to override it

    13

    Original web.xml

    Faces Servlet

    javax.faces.webapp.FacesServlet

    Faces Servlet

    *. sf< url- attern>

    javax.faces.PROJECT_STAGE

    Development

    index. s < welcome-file>.

    index.html

    14 These settings are described in tutorial section on JSF 2.0 setup.

  • 7/31/2019 JSF2 Using Spring

    7/24

    Original faces-config.xml

    - =" ". .

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"

    version="2.0">

    15 This file is introduced in tutorial section on JSF 2.0 setup.

    Configuring the App for Spring:.

    ContextLoaderListenerThis listener runs when the app is first started. It

    instantiates the ApplicationContext (fromWEB-INF/a licationContext.xml and laces areference to it in the ServletContext

    You can retrieve this reference with the staticge equ re e pp ca on on ex me o oWebApplicationContextUtils

    Re uestContextListenerThis listener is needed if you declare any of your beans to

    be request-scoped or session-scoped .e., e scopes nstea o t e usua pr ng scopes o

    singleton or prototype

    16

  • 7/31/2019 JSF2 Using Spring

    8/24

    web.xml Settings

    org.springframework.web.context.ContextLoaderListener

    or .s rin framework.web.context.re uest.Re uestContextListener

    17

    Configuring JSF to Recognize

    Not good to call getBean It would be technically legal to get the

    ApplicationContext and call getBean explicitly (probablyfrom the backin beans action controller method . Butthis is a bad idea since JSF is geared around declaringbeans in config files only.

    a rea y suppor s epen ency n ec onThe managed-property element lets you insert other beans

    The only trick is to be able to refer to Spring beans

    Use DelegatingVariableResolverDeclare in faces-config.xml. Now, whenever JSF sees a

    bean name, it uses JSF rules first, then Spring rules next.18

  • 7/31/2019 JSF2 Using Spring

    9/24

    Configuring JSF to Recognize.

    - " .

    or .s rin framework.web. sf.Dele atin VariableResolver. . . .

    19

    2010 Marty Hall

    Beans in Two Config Files

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 7/31/2019 JSF2 Using Spring

    10/24

    Example: Overview

    Input form o ec s user an passwor

    Required

    Collects preferred foreground

    Optional

    Results pages ows name an a ance o cus omer

    with given ID Uses preferred colors

    orm re sp aye w errors : User ID or password missing

    Uses required and requiredMessage

    User ID is unknown Sets FacesMessage in action controller

    21

    Example: Overview (Continued)

    Service interfaceCustomerLookupService

    Maps customer IDs to Customers

    MapCustomerLookupService

    Uses fixed HashMap of a few sample customers Color preferences object

    ColorPreferences Stores the users foreground and background colors

    Backing bean (JSF managed bean)

    Needs the service implementation and color preferencesobject to be injected into it22

  • 7/31/2019 JSF2 Using Spring

    11/24

    Example: Overview (Continued)

    applicationContext.xmlDefines color preferences object and injects initial

    foreground and background colors into it

    Defines customer lookup service as a Map and injects allthe keys and values into it

    n s ng e on scope

    faces-config.xml

    Creates the main backing bean in request scope and

    injects the two Spring beans (lookup service and colorpreferences object) into it.

    But, a later example will move even this part toapplicationContext.xml23

    web.xml: Defining Listeners

    org.springframework.web.context.ContextLoaderListener

    Loads /WEB-INF/applicationContext.xml and puts reference to it in servlet context. Can be

    accessed with WebApplicationContextUtils.getRequiredWebApplicationContext

    org.springframework.web.context.request.RequestContextListener

    Lets you give request or session scopes to beans in

    24

    applicationContext.xml. If you dont use these scopes, this listener is

    not required. But you should probably have this entry commentedout in web.xml just in case you want those scopes later.

  • 7/31/2019 JSF2 Using Spring

    12/24

    Color Preferences Bean

    public class ColorPreferences implements Serializable {

    public String getForeground() {return(foreground);

    In Web apps in general, session da ta

    should be Serializable. This is partly to

    support distributed apps, but the moreimportant reason is that Tomcat and other

    servers will let session data live across

    }

    public voidsetForeground(String foreground) {

    this.foreground = foreground;

    .

    The foreground and background

    properties are tied to the textfields.

    }

    // getBackgroundandsetBackground

    String style =

    String.format("color: %s; background-color: %s",fore round, back round);

    return(style);

    }

    }25

    h:body does not support the bgcolor and text attributes

    that the regular body tag has. So, produce a CSS style

    string to supply to the style attribute of h:body.

    Customer Lookup Service:

    public interface CustomerLookupService {

    public Customer findCustomer(String id);

    }

    26

  • 7/31/2019 JSF2 Using Spring

    13/24

    Customer Lookup Service:

    public class MapCustomerLookupService

    implements CustomerLookupService {

    private Map sampleCustomers;

    public Map getSampleCustomers() {

    }

    public voidsetSampleCustomers(Map sampleCustomers) {

    this.sampleCustomers = sampleCustomers;

    }

    public Customer findCustomer(String id) {

    if (id == null) {

    This will be set via

    in applicationContext.xml

    id = "unknown";

    }

    return(sampleCustomers.get(id.toLowerCase()));

    public Customer getRichestCustomer() { }

    }27

    Customer Beanpublic class Customer {

    , ,

    private double balance;

    public String getFormattedBalance() {

    re urn r ng. orma ,. , ge a ance ;

    }

    }

    28

  • 7/31/2019 JSF2 Using Spring

    14/24

    Backing Bean: Properties

    public class CustomerBackingBean {rivate Strin in utID assword;

    Corresponding setters called

    by JSF when form submitted.

    private Customer customer;

    private ColorPreferences colorPreferences;private CustomerLookupService lookupService;

    Filled in by action controller method

    (shown on next slide).

    // Getters and settersSetter methods called when bean created

    ecause o manage - ean-propery n

    faces-config.xml. The incoming values are

    Spring beans.

    29

    Backing Bean:

    public String findBalance() {

    customer = looku Service.findCustomer(in utID);

    FacesContext context =

    FacesContext.getCurrentInstance();

    if (customer == null) {Since the form used prependId="false", this is just the id

    of the h:inputText element. Otherwise, you would put

    "formId:customerId" here.

    String message =

    String.format("Unknown ID '%s'", inputID);

    context.addMessage("customerId", new FacesMessage(message));

    }if (!password.equals("secret")) {

    String message = "Incorrect password";

    context.addMessage("password", new FacesMessage(message));

    }

    if (context.getMessageList().size() > 0) {

    return(null);

    } else {

    return ("show-balance");

    }

    }30

  • 7/31/2019 JSF2 Using Spring

    15/24

    faces-config: Variable Resolver

    org.springframework.web.jsf.DelegatingVariableResolver

    31

    faces-config: Backing Bean

    - - - -

    coreservlets.CustomerBackingBean

    < mana ed-bean-class>

    request

    < ro ert -name>looku Service#{sampleLookupService}

    colorPreferences

    #{colorPreferences}

    Gets the Spring bean called sampleLookupService

    and passes it to the setLookupService method of the

    JSF backing bean called formBean (i.e., injects it

    into the looku Service ro ert .

    32

    .

    Gets the Spring bean called colorPreferences and injects

    it into the colorPreferences property of the backing bean.

  • 7/31/2019 JSF2 Using Spring

    16/24

    applicationContext.xml:

    < ro ert name="fore round" value="black" >

    33

    applicationContext.xml:

    < ro ert name="lastName" value="Johnson" >

    < bean>

    34

  • 7/31/2019 JSF2 Using Spring

    17/24

    Input Form: Top.

    " ". .

    Using prependId makes it easier to refer to the inputelement ID in the action controller method when setting acustom error message.

    * Customer ID:

    :message or= cus omer s y e ass= error


    35

    If no user ID is entered, the form is redisplayed and Missing customer ID is shown. If an

    unknown ID is entered, the action controller method sets a custom F acesMessage and

    returns null so that the form is redisplayed and Unknown ID is shown. If a recognized ID is

    entered, will navigate to page showing name and balance (using preferred colors).

    Input Form: Bottom.

    * Password:


    Preferred foreground color:


    Preferred background color:


    36

  • 7/31/2019 JSF2 Using Spring

    18/24

    Input Form (Initial Result)

    37

    Results Page.

    ...

    " ". .

    Spring Bank: Your Balance

    < table>

    ID: #{formBean.customer.customerID}First name: #{formBean.customer.firstName}

    Last name: #{formBean.customer.lastName}

    Balance: #{formBean.customer.formattedBalance}

    38

  • 7/31/2019 JSF2 Using Spring

    19/24

    Results: Bad Data

    39

    Results: Good Data

    40

  • 7/31/2019 JSF2 Using Spring

    20/24

    2010 Marty Hall

    Beans in One Config File

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Overview

    Issue with previous exampleBeans defined in two different files

    Some using Spring syntax, some using JSF syntax

    applicationContext.xml

    Defines the Spring beans as before Defines session-scoped ColorPreferences and

    singleton-scoped CustomerLookupService

    Also defines the backing bean

    faces-config.xml Defines only non-beans entries

    , , , .

    Functionality and appearance Exactly the same as in previous app

    42

  • 7/31/2019 JSF2 Using Spring

    21/24

    Changes from Previous

    faces-config.xmlDeleted the entire entry

    applicationContext.xml e t e o ow ng s mp er entry

    < ro ert name="colorPreferences" ref="colorPreferences"/>

    Two advantages epen ency n ec on syn ax s s mp er an more power u

    All bean definitions in the same file

    43

    faces-config.xml

    org.springframework.web.jsf.DelegatingVariableResolver

    44

  • 7/31/2019 JSF2 Using Spring

    22/24

    applicationContext.xml

    /bean>

    bean id="formBean"

    class="coreservlets.CustomerBackingBean"

    scope="request">

    " " " "

    /beans>

    45

    Results: Bad Data

    46

  • 7/31/2019 JSF2 Using Spring

    23/24

    Results: Good Data

    47

    2010 Marty Hall

    Wrap-up

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 7/31/2019 JSF2 Using Spring

    24/24

    Summary

    Basic setupStart with same setup as regular JSF apps

    Add Spring JAR files and applicationContext.xml

    aces-con g.xmDeclare DelegatingVariableResolver

    Declare Spring beans in applicationContext.xml

    Declare backin beans in faces-confi .xml Refer to Spring beans with managed-bean-property

    Option 2Declare all beans in applicationContext.xml

    Refer to other beans with ref and normal Spring syntax49

    2010 Marty Hall

    Questions?

    Customized Java EE Training: http://courses coreservlets com/