SlideShare une entreprise Scribd logo
1  sur  38
Télécharger pour lire hors ligne
Unit 7: Design Patterns and Frameworks

 A framework “is an abstraction in which common code
    providing generic functionality can be selectively overridden
    or specialized by user code providing specific functionality.”
    (from Wikipedia)

 Here we are going to consider 3 MVC-based Web frameworks
    for Java:
       Struts 1
       Spring MVC
       JavaServer Faces




dsbw 2011/2012 q1                                                    1
Struts 1: Overview




dsbw 2011/2012 q1    2
dsbw 2011/2012 q1   3
dsbw 2011/2012 q1   4
Struts 1: Terminology wrt. J2EE Core Patterns


                       Struts 1        J2EE Core Patterns
                    Implementation            Concept

            ActionServlet            Front Controller

            RequestProcessor         Application Controller

            UserAction               Businesss Helper

            ActionMapping            View Mapper

            ActionForward            View Handle




dsbw 2011/2012 q1                                             5
Struts 1: Example - WoT’s New User




dsbw 2011/2012 q1                    6
Struts 1: Example – user_registration.vm (Velocity template)

<html><head> .... </head>
<body>
…
<form action = “register.do" method="post">
      User’s Nickname:
      <input name=“username"
        value="$!registrationForm.username" size=40>
        $!errors.wrongUsername.get(0)
      Password :
      <input name=“userpassword“ size=40>
        $!errors.wrongPassword.get(0)
      <!–- CAPTCHA CODE -->
      <input type="submit" name="insert" value=“insert">
</form>
<center>$!errors.regDuplicate.get(0)</center>
</body></html>

dsbw 2011/2012 q1                                              7
Struts 1: Example – Form validation




dsbw 2011/2012 q1                     8
Struts 1: Example - RegistrationForm
public class RegistrationForm extends ActionForm
{
   protected String reg_username;
   // ... The remaining form attributes + getter & setter methods


    public void reset(ActionMapping mapping,
                      HttpServletRequest request) {
     /* ... Attribute initialization */ }

    public ActionErrors validate(ActionMapping mapping,
             HttpServletRequest request) {
      ActionErrors errors = new ActionErrors();
      if (reg_username == null || reg_username.equals("")) {
        errors.add(“wrongUsername",
                new ActionMessage("errors.username”));
      }
      // .... Remaining validations
      return errors; }
}


dsbw 2011/2012 q1                                                   9
Struts 1: Example – Error Messages (Message.properties file)

errors.username=(*) Username required

errors.password=(*) Password required

errors.regCAPTCHA=(*) Invalid CAPTCHA values

errors.duplicateUser = Username '{0}' is already taken by
    another user




dsbw 2011/2012 q1                                              10
Struts 1: Example – Application Error (duplicated username)




dsbw 2011/2012 q1                                             11
Struts 1: Example - UserAction
public class RegisterAction extends Action {
public ActionForward execute(ActionMapping mapping,
                     ActionForm form, HttpServletRequest request,
                     HttpServletResponse response)
{ String username = ((RegistrationForm) form).getReg_username();
   String password = ((RegistrationForm) form).getReg_password();
   Connection dbConnection = … ;
   try {
    Transaction trans = Transaction.newTransaction("RegisterTrans");
    trans.getParameterMap().put("dbConnection", dbConnection);
    trans.getParameterMap().put("username", username);
    trans.getParameterMap().put("password", password);
    trans.execute();
    request.getSession().setAttribute("loggedUserNAME",username);
    request.getSession().setAttribute("loggedUserID",trans.getPara
    meterMap().get("userID"));
    return (mapping.findForward("success"));
         }

dsbw 2011/2012 q1                                                      12
Struts 1: Example – UserAction (cont.)
    catch (BusinessException ex)
    {
      if (ex.getMessageList().elementAt(0).startsWith("Username"))
         {
           ActionMessages errors = new ActionMessages();
           errors.add("regDuplicate",
               new ActionMessage("errors.duplicateUser",username));
           this.saveErrors(request, errors);
           form.reset(mapping,request);
           return (mapping.findForward("duplicateUser"));
         }
       else {
         request.setAttribute("theList",ex.getMessageList());
         return (mapping.findForward("failure"));
         }
    }
}
}

dsbw 2011/2012 q1                                                 13
Struts 1: Example - struts-config.xml (fragment)

<action-mappings>
  <action path="/register"
        type="woTFront.RegisterAction"
        name="registrationForm"
        scope="request"
        validate="true"
        input="/user_registration.vm">
       <forward name="failure" path="/error.vm"/>
       <forward name="duplicateUser“
                path="/user_registration.vm"/>
       <forward name="success"
                path="/wall" redirect="true"/>
   </action>
…
</action-mappings>


dsbw 2011/2012 q1                                   14
Struts 1: Example - web.xml (fragment)
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
      org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-
  config.xml</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>


dsbw 2011/2012 q1                              15
Struts 1: Example - web.xml (fragment, cont.)
<servlet>
    <servlet-name>velocity</servlet-name>
    <servlet-class>
        org.apache.velocity.tools.view.servlet.VelocityViewServlet
   </servlet-class>
    <init-param>
      <param-name>org.apache.velocity.toolbox</param-name>
      <param-value>/WEB-INF/toolbox.xml</param-value>
    </init-param>
    <init-param>
      <param-name>org.apache.velocity.properties</param-name>
      <param-value>/WEB-INF/velocity.properties</param-value>
    </init-param>
  </servlet>
 <servlet-mapping>
    <servlet-name>velocity</servlet-name>
    <url-pattern>*.vm</url-pattern>
  </servlet-mapping>

dsbw 2011/2012 q1                                                16
Struts 2
 Struts 2 vs Struts 1 (according to struts.apache.org/2.x)
    Enhanced Results - Unlike ActionForwards, Struts 2 Results can
     actually help prepare the response.
    Enhanced Tags - Struts2 tags don't just output data, but provide
     stylesheet-driven markup, so that we consistent pages can be created
     with less code.
    POJO forms - No more ActionForms: we can use any JavaBean we like
     or put properties directly on our Action classes.
    POJO Actions - Any class can be used as an Action class. Even the
     interface is optional!
    First-class AJAX support - The AJAX theme gives interactive
     applications a boost.
    Easy-to-test Actions – Struts 2 Actions are HTTP independent and can
     be tested without resorting to mock objects.
    Intelligent Defaults - Most framework configuration elements have a
     default value that we can set and forget.

dsbw 2011/2012 q1                                                       17
Struts 2: Tagging example

                    <s:actionerror/>
                    <s:form action="Profile_update" validate="true">
                    <s:textfield label="Username" name="username"/>
                    <s:password label="Password" name="password"/>
                    <s:password label="(Repeat) Password"
                        name="password2"/>
                    <s:textfield label="Full Name" name="fullName"/>
                    <s:textfield label="From Address"
                        name="fromAddress"/>
                    <s:textfield label="Reply To Address"
                        name="replyToAddress"/>
                    <s:submit value="Save" name="Save"/>
                    <s:submit action="Register_cancel" value="Cancel"
                        name="Cancel" onclick="form.onsubmit=null"/>
                        </s:form>

dsbw 2011/2012 q1                                                       18
Spring MVC
 Spring's own implementation of the Front Controller Pattern
 Flexible request mapping and handling

 Full forms support

 Supports several view technologies
         JSP/Tiles, Velocity, FreeMarker
 Support integration with other MVC frameworks
         Struts, Tapestry, JavaServerFaces, WebWork
 Provides a JSP Tag Library




dsbw 2011/2012 q1                                               19
Spring Framework Architecture


                                                              Spring Web
                                 Spring ORM                WebApplicationContext
                                 Hibernate support           Struts integration
                                   iBatis support            Tiles integration       Spring MVC
                                    JDO support                Web utilities
       Spring AOP                                                                  Web MVC Framework
     AOP infrastructure                                                                JSP support
      Metadata support                                                             Velocity/FreeMarker
    Declarative transaction                                                              support
        management                                                                  PFD/Excel support
                                 Spring DAO                Spring Context
                              Transaction Infrastructure     ApplicationContext
                                   JDBC support              JNDI, EJB support
                                   DAO support                   Remoting




                                                  Spring Core
                                                   IoC Container




dsbw 2011/2012 q1                                                                                        20
Spring MVC: Request Lifecycle




dsbw 2011/2012 q1               21
Spring MVC: Terminology wrt. J2EE Core Patterns


                    Spring MVC      J2EE Core Patterns
                                          Concept

            DispatcherServlet    Front Controller /
                                 Application Controller

            HandlerMapping       Command Mapper

            ModelAndView         View Handle /
                                 Presentation Model

            ViewResolver         View Mapper

            Controller           Business Helper

dsbw 2011/2012 q1                                         22
Spring MVC: Setting Up
1.    Add the Spring dispatcher servlet to the web.xml
2.    Configure additional bean definition files in web.xml
3.    Write Controller classes and configure them in a bean
      definition file, typically META-INF/<appl>-servlet.xml
4.    Configure view resolvers that map view names to to views
      (JSP, Velocity etc.)
5.    Write the JSPs or other views to render the UI




dsbw 2011/2012 q1                                                23
Spring MVC: Controllers
public class ListCustomersController implements Controller {
   private CustomerService customerService;
   public void setCustomerService(CustomerService
                                  customerService)
   {    this.customerService = customerService; }

    public ModelAndView handleRequest(HttpServletRequest req,
                          HttpServletResponse res) throws Exception
    {
         return new ModelAndView(“customerList”, “customers”,

    customerService.getCustomers());
    }
}

 ModelAndView object is simply a combination of a named
    view and a Map of objects that are introduced into the
    request by the dispatcher

dsbw 2011/2012 q1                                                 24
Spring MVC: Controllers (cont.)
 Interface based
         Do not have to extend any base classes (as in Struts)
 Have option of extending helpful base classes
       Multi-Action Controllers
       Command Controllers
               Dynamic binding of request parameters to POJO (no ActionForms)
         Form Controllers
               Hooks into cycle for overriding binding, validation, and inserting
                reference data
               Validation (including support for Commons Validation)
               Wizard style controller




dsbw 2011/2012 q1                                                                    25
JavaServer Faces (JSF)
 Sun’s “Official” Java-based Web application framework
 Specifications:
       JSF 1.0 (11-03-2004)
       JSF 1.1 (25-05-2004)
       JSF 1.2 (11-05-2006)
       JSF 2.0 (28-06-2009)

 Main characteristics:
         UI component state management across requests
         Mechanism for wiring client-generated events to server side
          application code
         Allow custom UI components to be easily built and re-used
         A well-defined request processing lifecycle
         Designed to be tooled
dsbw 2011/2012 q1                                                       26
JSF: Application Architecture


                    Servlet Container
Client
                    JSF Application
Devices

                                        Business    DB
 Phone
                                         Objects
                    JSF Framework
   PDA
                                         Model
                                         Objects
 Laptop                                              EJB
                                                   Container




dsbw 2011/2012 q1                                              27
JSF framework: MVC

             Request                                Response




                    FacesServlet
                                   Component          Model Objects
                                     Tree           Managed JavaBeans

                                                                     View
                                   Resources            Delegates
  Config                            JavaBeans           Converters
                                   Property Files       Validators
                                       XML              Renderers


                     Action
                    Handlers       Business Objects
Controller          & Event                 EJB          Model
                    Listeners               JDO
                                           JDBC


dsbw 2011/2012 q1                                                       28
JSF: Request Processing Lifecycle

                                            Response Complete               Response Complete



Request     Restore
                         Apply Request         Process         Process            Process
           Component
                             Value              Events        Validations          Events
              Tree

                              Render Response

                       Response Complete                 Response Complete

Response    Render      Process           Invoke             Process          Update Model
           Response      Events          Application          Events             Values


                          Conversion Errors


                                                                Validation or
                                                                Conversion Errors




dsbw 2011/2012 q1                                                                           29
JSF: Request Processing Lifecycle
 Restore Component Tree:
       The requesting page’s component tree is retrieved/recreated.
       Stateful information about the page (if existed) is added to the
        request.
 Apply Request Value:
       Each component in the tree extracts its new value from the
        request parameters by using its decode method.
       If the conversion of the value fails, an error message associated
        with the component is generated and queued .
       If events have been queued during this phase, the JSF
        implementation broadcasts the events to interested listeners.
 Process Validations:
         The JSF implementation processes all validators registered on
          the components in the tree. It examines the component
          attributes that specify the rules for the validation and compares
          these rules to the local value stored for the component.
dsbw 2011/2012 q1                                                          30
JSF: Request Processing Lifecycle
 Update Model Values:
       The JSF implementation walks the component tree and set the
        corresponding model object properties to the components'
        local values.
       Only the bean properties pointed at by an input component's
        value attribute are updated
 Invoke Application:
       Action listeners and actions are invoked
       The Business Logic Tier may be called

 Render Response:
         Render the page and send it back to client



dsbw 2011/2012 q1                                                     31
JSF: Anatomy of a UI Component


                                        Event
                                       Handling                  Render
              Model

                              binds                   has
                                            has

         Id             has                            has
    Local Value                       UIComponent                 Validators
   Attribute Map
                                                         has
                                           has

                          Child
                                                    Converters
                      UIComponent




dsbw 2011/2012 q1                                                              32
JSF: Standard UI Components
 UIInput
                        UICommand
 UIOutput
                        UIForm
 UISelectBoolean
                        UIColumn
 UISelectItem
                        UIData
 UISelectMany
                        UIPanel
 UISelectOne
 UISelectMany

 UIGraphic




dsbw 2011/2012 q1                    33
JSF: HTML Tag Library
 JSF Core Tag Library (prefix: f)
         Validator, Event Listeners, Converters


 JSF Standard Library (prefix: h)
         Express UI components in JSP




dsbw 2011/2012 q1                                  34
JSF: HTML Tag Library
<f:view>
<h:form id=”logonForm”>
  <h:panelGrid columns=”2”>
    <h:outputLabel for=”username”>
      <h:outputText value=”Username:”/>
    </h:outputLabel>
    <h:inputText id=”username”
   value=”#{logonBean.username}”/>
    <h:outputLabel for=”password”>
      <h:outputText value=”Password:”/>
    </h:outputLabel>
    <h:inputSecret id=”password”
         value=”#{logonBean.password}”/>
    <h:commandButton
         id=”submitButton” type=”SUBMIT”
                action=”#{logonBean.logon}”/>
    <h:commandButton
        id=”resetButton” type=”RESET”/>
  </h:panelGrid>
</h:form>
</f:view>
   dsbw 2011/2012 q1                            35
JSF: Managed (Model) Bean
 Used to separate presentation from business logic

 Based on JavaBeans

 Similar to Struts ActionForm concept

 Can also be registered to handle events and conversion and
    validation functions

 UI Component binding example:
      <h:inputText id=”username”
         value=”#{logonBean.username}”/>




dsbw 2011/2012 q1                                              36
What’s new in JSF 2.0?
 New Page Declaration Language (PDL) based on Apache
    Facelets
 Custom components much easier to develop

 Improved Ajax integration and support




dsbw 2011/2012 q1                                       37
References
 Books:
         B. Siggelkow. Jakarta Struts Cookbook. O'Reilly, 2005
         J. Carnell, R. Harrop. Pro Jakarta Struts, 2nd Edition. Apress, 2004
         C. Walls, R. Breidenbach. Spring in Action. Manning, 2006.
         B. Dudney, J. Lehr, B. Willis, L. Mattingly. Mastering JavaServer Faces.
          Willey, 2004.
 Web sites:
         struts.apache.org
         rollerjm.free.fr/pro/Struts11.html
         www.springframework.org
         static.springframework.org/spring/docs/1.2.x/reference/mvc.html
         java.sun.com/javaee/javaserverfaces



dsbw 2011/2012 q1                                                                    38

Contenu connexe

Tendances

Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applicationselliando dias
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Fahad Golra
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsIMC Institute
 
JSF basics
JSF basicsJSF basics
JSF basicsairbo
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Courseguest764934
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (2/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (2/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (2/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (2/3)Carles Farré
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6Lokesh Singrol
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the clientSebastiano Armeli
 
Java EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJava EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJosh Juneau
 
Lecture 1: Introduction to JEE
Lecture 1:  Introduction to JEELecture 1:  Introduction to JEE
Lecture 1: Introduction to JEEFahad Golra
 

Tendances (20)

Struts course material
Struts course materialStruts course material
Struts course material
 
Unit 02: Web Technologies (1/2)
Unit 02: Web Technologies (1/2)Unit 02: Web Technologies (1/2)
Unit 02: Web Technologies (1/2)
 
Unit 10: XML and Beyond (Sematic Web, Web Services, ...)
Unit 10: XML and Beyond (Sematic Web, Web Services, ...)Unit 10: XML and Beyond (Sematic Web, Web Services, ...)
Unit 10: XML and Beyond (Sematic Web, Web Services, ...)
 
Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applications
 
Unit 04: From Requirements to the UX Model
Unit 04: From Requirements to the UX ModelUnit 04: From Requirements to the UX Model
Unit 04: From Requirements to the UX Model
 
Java server faces
Java server facesJava server faces
Java server faces
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
 
JSF basics
JSF basicsJSF basics
JSF basics
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Course
 
Introduction to jsf 2
Introduction to jsf 2Introduction to jsf 2
Introduction to jsf 2
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (2/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (2/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (2/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (2/3)
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6
 
Unit 01 - Introduction
Unit 01 - IntroductionUnit 01 - Introduction
Unit 01 - Introduction
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
 
TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the client
 
Jsf presentation
Jsf presentationJsf presentation
Jsf presentation
 
Java EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJava EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVC
 
Lecture 1: Introduction to JEE
Lecture 1:  Introduction to JEELecture 1:  Introduction to JEE
Lecture 1: Introduction to JEE
 

Similaire à Unit 07: Design Patterns and Frameworks (3/3)

PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Arun Gupta
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0Arun Gupta
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Matt Raible
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web FrameworkLuther Baker
 
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)Daniel Bryant
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJini Lee
 
Strutsjspservlet
Strutsjspservlet Strutsjspservlet
Strutsjspservlet Sagar Nakul
 

Similaire à Unit 07: Design Patterns and Frameworks (3/3) (20)

PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Struts Overview
Struts OverviewStruts Overview
Struts Overview
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
MVC
MVCMVC
MVC
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0
 
Jsf
JsfJsf
Jsf
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 
Stripes Framework
Stripes FrameworkStripes Framework
Stripes Framework
 
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Strutsjspservlet
Strutsjspservlet Strutsjspservlet
Strutsjspservlet
 

Dernier

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Dernier (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Unit 07: Design Patterns and Frameworks (3/3)

  • 1. Unit 7: Design Patterns and Frameworks  A framework “is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality.” (from Wikipedia)  Here we are going to consider 3 MVC-based Web frameworks for Java:  Struts 1  Spring MVC  JavaServer Faces dsbw 2011/2012 q1 1
  • 2. Struts 1: Overview dsbw 2011/2012 q1 2
  • 5. Struts 1: Terminology wrt. J2EE Core Patterns Struts 1 J2EE Core Patterns Implementation Concept ActionServlet Front Controller RequestProcessor Application Controller UserAction Businesss Helper ActionMapping View Mapper ActionForward View Handle dsbw 2011/2012 q1 5
  • 6. Struts 1: Example - WoT’s New User dsbw 2011/2012 q1 6
  • 7. Struts 1: Example – user_registration.vm (Velocity template) <html><head> .... </head> <body> … <form action = “register.do" method="post"> User’s Nickname: <input name=“username" value="$!registrationForm.username" size=40> $!errors.wrongUsername.get(0) Password : <input name=“userpassword“ size=40> $!errors.wrongPassword.get(0) <!–- CAPTCHA CODE --> <input type="submit" name="insert" value=“insert"> </form> <center>$!errors.regDuplicate.get(0)</center> </body></html> dsbw 2011/2012 q1 7
  • 8. Struts 1: Example – Form validation dsbw 2011/2012 q1 8
  • 9. Struts 1: Example - RegistrationForm public class RegistrationForm extends ActionForm { protected String reg_username; // ... The remaining form attributes + getter & setter methods public void reset(ActionMapping mapping, HttpServletRequest request) { /* ... Attribute initialization */ } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (reg_username == null || reg_username.equals("")) { errors.add(“wrongUsername", new ActionMessage("errors.username”)); } // .... Remaining validations return errors; } } dsbw 2011/2012 q1 9
  • 10. Struts 1: Example – Error Messages (Message.properties file) errors.username=(*) Username required errors.password=(*) Password required errors.regCAPTCHA=(*) Invalid CAPTCHA values errors.duplicateUser = Username '{0}' is already taken by another user dsbw 2011/2012 q1 10
  • 11. Struts 1: Example – Application Error (duplicated username) dsbw 2011/2012 q1 11
  • 12. Struts 1: Example - UserAction public class RegisterAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String username = ((RegistrationForm) form).getReg_username(); String password = ((RegistrationForm) form).getReg_password(); Connection dbConnection = … ; try { Transaction trans = Transaction.newTransaction("RegisterTrans"); trans.getParameterMap().put("dbConnection", dbConnection); trans.getParameterMap().put("username", username); trans.getParameterMap().put("password", password); trans.execute(); request.getSession().setAttribute("loggedUserNAME",username); request.getSession().setAttribute("loggedUserID",trans.getPara meterMap().get("userID")); return (mapping.findForward("success")); } dsbw 2011/2012 q1 12
  • 13. Struts 1: Example – UserAction (cont.) catch (BusinessException ex) { if (ex.getMessageList().elementAt(0).startsWith("Username")) { ActionMessages errors = new ActionMessages(); errors.add("regDuplicate", new ActionMessage("errors.duplicateUser",username)); this.saveErrors(request, errors); form.reset(mapping,request); return (mapping.findForward("duplicateUser")); } else { request.setAttribute("theList",ex.getMessageList()); return (mapping.findForward("failure")); } } } } dsbw 2011/2012 q1 13
  • 14. Struts 1: Example - struts-config.xml (fragment) <action-mappings> <action path="/register" type="woTFront.RegisterAction" name="registrationForm" scope="request" validate="true" input="/user_registration.vm"> <forward name="failure" path="/error.vm"/> <forward name="duplicateUser“ path="/user_registration.vm"/> <forward name="success" path="/wall" redirect="true"/> </action> … </action-mappings> dsbw 2011/2012 q1 14
  • 15. Struts 1: Example - web.xml (fragment) <servlet> <servlet-name>action</servlet-name> <servlet-class> org.apache.struts.action.ActionServlet </servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts- config.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> dsbw 2011/2012 q1 15
  • 16. Struts 1: Example - web.xml (fragment, cont.) <servlet> <servlet-name>velocity</servlet-name> <servlet-class> org.apache.velocity.tools.view.servlet.VelocityViewServlet </servlet-class> <init-param> <param-name>org.apache.velocity.toolbox</param-name> <param-value>/WEB-INF/toolbox.xml</param-value> </init-param> <init-param> <param-name>org.apache.velocity.properties</param-name> <param-value>/WEB-INF/velocity.properties</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>velocity</servlet-name> <url-pattern>*.vm</url-pattern> </servlet-mapping> dsbw 2011/2012 q1 16
  • 17. Struts 2  Struts 2 vs Struts 1 (according to struts.apache.org/2.x)  Enhanced Results - Unlike ActionForwards, Struts 2 Results can actually help prepare the response.  Enhanced Tags - Struts2 tags don't just output data, but provide stylesheet-driven markup, so that we consistent pages can be created with less code.  POJO forms - No more ActionForms: we can use any JavaBean we like or put properties directly on our Action classes.  POJO Actions - Any class can be used as an Action class. Even the interface is optional!  First-class AJAX support - The AJAX theme gives interactive applications a boost.  Easy-to-test Actions – Struts 2 Actions are HTTP independent and can be tested without resorting to mock objects.  Intelligent Defaults - Most framework configuration elements have a default value that we can set and forget. dsbw 2011/2012 q1 17
  • 18. Struts 2: Tagging example <s:actionerror/> <s:form action="Profile_update" validate="true"> <s:textfield label="Username" name="username"/> <s:password label="Password" name="password"/> <s:password label="(Repeat) Password" name="password2"/> <s:textfield label="Full Name" name="fullName"/> <s:textfield label="From Address" name="fromAddress"/> <s:textfield label="Reply To Address" name="replyToAddress"/> <s:submit value="Save" name="Save"/> <s:submit action="Register_cancel" value="Cancel" name="Cancel" onclick="form.onsubmit=null"/> </s:form> dsbw 2011/2012 q1 18
  • 19. Spring MVC  Spring's own implementation of the Front Controller Pattern  Flexible request mapping and handling  Full forms support  Supports several view technologies  JSP/Tiles, Velocity, FreeMarker  Support integration with other MVC frameworks  Struts, Tapestry, JavaServerFaces, WebWork  Provides a JSP Tag Library dsbw 2011/2012 q1 19
  • 20. Spring Framework Architecture Spring Web Spring ORM WebApplicationContext Hibernate support Struts integration iBatis support Tiles integration Spring MVC JDO support Web utilities Spring AOP Web MVC Framework AOP infrastructure JSP support Metadata support Velocity/FreeMarker Declarative transaction support management PFD/Excel support Spring DAO Spring Context Transaction Infrastructure ApplicationContext JDBC support JNDI, EJB support DAO support Remoting Spring Core IoC Container dsbw 2011/2012 q1 20
  • 21. Spring MVC: Request Lifecycle dsbw 2011/2012 q1 21
  • 22. Spring MVC: Terminology wrt. J2EE Core Patterns Spring MVC J2EE Core Patterns Concept DispatcherServlet Front Controller / Application Controller HandlerMapping Command Mapper ModelAndView View Handle / Presentation Model ViewResolver View Mapper Controller Business Helper dsbw 2011/2012 q1 22
  • 23. Spring MVC: Setting Up 1. Add the Spring dispatcher servlet to the web.xml 2. Configure additional bean definition files in web.xml 3. Write Controller classes and configure them in a bean definition file, typically META-INF/<appl>-servlet.xml 4. Configure view resolvers that map view names to to views (JSP, Velocity etc.) 5. Write the JSPs or other views to render the UI dsbw 2011/2012 q1 23
  • 24. Spring MVC: Controllers public class ListCustomersController implements Controller { private CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { return new ModelAndView(“customerList”, “customers”, customerService.getCustomers()); } }  ModelAndView object is simply a combination of a named view and a Map of objects that are introduced into the request by the dispatcher dsbw 2011/2012 q1 24
  • 25. Spring MVC: Controllers (cont.)  Interface based  Do not have to extend any base classes (as in Struts)  Have option of extending helpful base classes  Multi-Action Controllers  Command Controllers  Dynamic binding of request parameters to POJO (no ActionForms)  Form Controllers  Hooks into cycle for overriding binding, validation, and inserting reference data  Validation (including support for Commons Validation)  Wizard style controller dsbw 2011/2012 q1 25
  • 26. JavaServer Faces (JSF)  Sun’s “Official” Java-based Web application framework  Specifications:  JSF 1.0 (11-03-2004)  JSF 1.1 (25-05-2004)  JSF 1.2 (11-05-2006)  JSF 2.0 (28-06-2009)  Main characteristics:  UI component state management across requests  Mechanism for wiring client-generated events to server side application code  Allow custom UI components to be easily built and re-used  A well-defined request processing lifecycle  Designed to be tooled dsbw 2011/2012 q1 26
  • 27. JSF: Application Architecture Servlet Container Client JSF Application Devices Business DB Phone Objects JSF Framework PDA Model Objects Laptop EJB Container dsbw 2011/2012 q1 27
  • 28. JSF framework: MVC Request Response FacesServlet Component Model Objects Tree Managed JavaBeans View Resources Delegates Config JavaBeans Converters Property Files Validators XML Renderers Action Handlers Business Objects Controller & Event EJB Model Listeners JDO JDBC dsbw 2011/2012 q1 28
  • 29. JSF: Request Processing Lifecycle Response Complete Response Complete Request Restore Apply Request Process Process Process Component Value Events Validations Events Tree Render Response Response Complete Response Complete Response Render Process Invoke Process Update Model Response Events Application Events Values Conversion Errors Validation or Conversion Errors dsbw 2011/2012 q1 29
  • 30. JSF: Request Processing Lifecycle  Restore Component Tree:  The requesting page’s component tree is retrieved/recreated.  Stateful information about the page (if existed) is added to the request.  Apply Request Value:  Each component in the tree extracts its new value from the request parameters by using its decode method.  If the conversion of the value fails, an error message associated with the component is generated and queued .  If events have been queued during this phase, the JSF implementation broadcasts the events to interested listeners.  Process Validations:  The JSF implementation processes all validators registered on the components in the tree. It examines the component attributes that specify the rules for the validation and compares these rules to the local value stored for the component. dsbw 2011/2012 q1 30
  • 31. JSF: Request Processing Lifecycle  Update Model Values:  The JSF implementation walks the component tree and set the corresponding model object properties to the components' local values.  Only the bean properties pointed at by an input component's value attribute are updated  Invoke Application:  Action listeners and actions are invoked  The Business Logic Tier may be called  Render Response:  Render the page and send it back to client dsbw 2011/2012 q1 31
  • 32. JSF: Anatomy of a UI Component Event Handling Render Model binds has has Id has has Local Value UIComponent Validators Attribute Map has has Child Converters UIComponent dsbw 2011/2012 q1 32
  • 33. JSF: Standard UI Components  UIInput  UICommand  UIOutput  UIForm  UISelectBoolean  UIColumn  UISelectItem  UIData  UISelectMany  UIPanel  UISelectOne  UISelectMany  UIGraphic dsbw 2011/2012 q1 33
  • 34. JSF: HTML Tag Library  JSF Core Tag Library (prefix: f)  Validator, Event Listeners, Converters  JSF Standard Library (prefix: h)  Express UI components in JSP dsbw 2011/2012 q1 34
  • 35. JSF: HTML Tag Library <f:view> <h:form id=”logonForm”> <h:panelGrid columns=”2”> <h:outputLabel for=”username”> <h:outputText value=”Username:”/> </h:outputLabel> <h:inputText id=”username” value=”#{logonBean.username}”/> <h:outputLabel for=”password”> <h:outputText value=”Password:”/> </h:outputLabel> <h:inputSecret id=”password” value=”#{logonBean.password}”/> <h:commandButton id=”submitButton” type=”SUBMIT” action=”#{logonBean.logon}”/> <h:commandButton id=”resetButton” type=”RESET”/> </h:panelGrid> </h:form> </f:view> dsbw 2011/2012 q1 35
  • 36. JSF: Managed (Model) Bean  Used to separate presentation from business logic  Based on JavaBeans  Similar to Struts ActionForm concept  Can also be registered to handle events and conversion and validation functions  UI Component binding example: <h:inputText id=”username” value=”#{logonBean.username}”/> dsbw 2011/2012 q1 36
  • 37. What’s new in JSF 2.0?  New Page Declaration Language (PDL) based on Apache Facelets  Custom components much easier to develop  Improved Ajax integration and support dsbw 2011/2012 q1 37
  • 38. References  Books:  B. Siggelkow. Jakarta Struts Cookbook. O'Reilly, 2005  J. Carnell, R. Harrop. Pro Jakarta Struts, 2nd Edition. Apress, 2004  C. Walls, R. Breidenbach. Spring in Action. Manning, 2006.  B. Dudney, J. Lehr, B. Willis, L. Mattingly. Mastering JavaServer Faces. Willey, 2004.  Web sites:  struts.apache.org  rollerjm.free.fr/pro/Struts11.html  www.springframework.org  static.springframework.org/spring/docs/1.2.x/reference/mvc.html  java.sun.com/javaee/javaserverfaces dsbw 2011/2012 q1 38