SlideShare uma empresa Scribd logo
1 de 33
Introduction to MVC and the
 Jakarta Struts Framework
        By Gyanendra Dwivedi
         Software Consultant
What is MVC
 • The Model View Controller design pattern is a technique used to
   separate Business logic/state (the Model) from User Interface
   (the View) and program progression/flow (the Control).
 • This pattern is very useful when it comes to modern web
   development:
     o The majority of modern, high usage websites are dynamically
       driven.
     o People well skilled at presentation (HTML writers) seldom know how
       to develop back-end solutions and visa versa.
     o Separating business rules from presentation is good no matter what
       environment you develop in be it web or desktop.




Feb 11, 2003            Introduction to Jakarta Struts –
                              Gyanendra Dwivedi
What is MVC (cont…)
 • The View
     o   The view is how data is represented to the user. For instance the
         view in a web application may be an HTML page, an image or other
         media
 • The Model
     o   The model represents the data in the system. For instance, a model
         might represent the properties associated with a user’s profile
 • The Controller
     o   The controller is the glue between the model and the view. It is
         responsible for controlling the flow of the program as well as
         processing updates from the model to the view and visa versa




Feb 11, 2003               Introduction to Jakarta Struts -
                                 Gyanendra Dwivedi
What is MVC (cont…)

                               User



                    View               Controller



                             Model



Feb 11, 2003       Introduction to Jakarta Struts -
                         Gyanendra Dwivedi
What is MVC (cont…)



                                  User



               View                                  Controller


                               Model
Feb 11, 2003          Introduction to Jakarta Struts -
                            Gyanendra Dwivedi
Benefits of MVC
 •   Promotes Modularity
 •   Multiple views
 •   Abstraction
 •   Allows application to be defined in a flow-chart, use-case or
     activity diagram which is more easily transferred to
     implementation.




Feb 11, 2003             Introduction to Jakarta Struts -
                               Gyanendra Dwivedi
Designing an MVC App.
 • Let’s try designing an application from scratch
 • The application will be a message board where users can view
   messages and post messages
 • The application will require that a user has an account setup with
   the message board before posting a message, but an account is
   not required for viewing a message.
 • The basic components we must implement for this message
   board are:
     o   User profile
     o   Logon/authentication
     o   Message List
     o   Message




Feb 11, 2003              Introduction to Jakarta Struts -
                                Gyanendra Dwivedi
Activity Diagrams
 • I find the UML activity diagrams to be the most useful construct
   for describing program flow.
 • Activity diagrams are much like flow charts, except a few new
   constructs are added such as describing concurrency as well as
   recursive elements.
 • Each node of the Activity Diagram can be thought of as a call to
   a “Controller” asking it to take you to the next step in the
   application




Feb 11, 2003           Introduction to Jakarta Struts -
                             Gyanendra Dwivedi
Activity Diagram: Create Profile


         Create Profile



                                                             Create
          Edit Profile
                            [invalid]
                                        ==                   Profile()

                [else]


          Save Profile




Feb 11, 2003              Introduction to Jakarta Struts -
                                Gyanendra Dwivedi
Activity Diagram: Logon


                 Login Form

Create
Profile()
               [new user]
                                               ==                  Logon()
                            [else]




Feb 11, 2003                         Introduction to Jakarta Struts -
                                           Gyanendra Dwivedi
Activity Diagram: View Msg.

          Show Msg.
            Board


                                                           Select
          Select Msg.             ==                       Msg()


         Display Msg.




Feb 11, 2003            Introduction to Jakarta Struts -
                              Gyanendra Dwivedi
Activity Diagram: Edit Msg.


               Select Msg()

                   Logon()
                                     [expired session]


                         [else]

                Create New
                   Msg.

                 Edit Msg.

                        [else]

                 Save Msg.

Feb 11, 2003   Introduction to Jakarta Struts -
                     Gyanendra Dwivedi
Jakarta Struts
 • In order to take advantage of the MVC design pattern in your
   applications a considerable framework must be in place.
 • Today we are going to learn about such a framework named
   Struts
 • Struts is an open source MVC framework developed by the
   Apache Jakarta project group.
 • Struts allows JSP/Servlet writers the ability to fashion their web
   applications using the MVC design pattern.
 • By designing your web application using Struts you allow:
     o   Architect the ability to design using the MVC pattern
     o   Developer to exploit the Struts framework when building the app.
     o   Web designer to be sheltered from learning how to program
                            http://jakarta.apache.org/struts/



Feb 11, 2003              Introduction to Jakarta Struts -
                                Gyanendra Dwivedi
Struts (cont…)

 • Struts takes the grunt work out of developing an MVC based web
   app.
 • The Struts framework provides a plethora of canned objects
   which can facilitate fundamental aspects of MVC, while allowing
   you to extend further as need suites
 • Struts allows you to configure a lot of the default framework
   objects through xml configuration files.
 • Our examples will use the Struts framework using the Apache
   Tomcat Servlet/JSP container.
                 http://jakarta.apache.org/tomcat/
 • Tomcat 3.2.1 provides a reference implementation of the Servlet
   specification 2.2 and JSP specification 1.1



Feb 11, 2003          Introduction to Jakarta Struts -
                            Gyanendra Dwivedi
Struts (cont…)
 • The components of MVC in Struts:
     o The View is usually defined as a JSP or HTML page.
     o The Model is usually defined as a Java object (sometimes called a
       bean).
     o The Controller is defined by a Java object which extends the
       org.apache.struts.action.Action class. The Action class is at the
       heart of the Struts framework.




Feb 11, 2003             Introduction to Jakarta Struts -
                               Gyanendra Dwivedi
Struts: The Model
 • To define a model in Struts is simple. Just create a java class
   and provide some functions.
 • Your model classes should be coded independent of the Struts
   framework to promote maximum code reuse by other
   applications (i.e. if you have to reference javax.servlet.* class in
   your model, you are doing something wrong)
 • Struts provides some default Model components, the most
   important of which is ActionForm.
 • If you create a Model class by extending the Struts ActionForm
   class, Struts will
     o Ensure your form bean is created when needed
     o Ensure form submittal directly updates your form object with the
       inputted values
     o Your controller object will be passed the form bean




Feb 11, 2003             Introduction to Jakarta Struts -
                               Gyanendra Dwivedi
The Model (cont…)
 • Struts will only handle models in an automatic fashion if you
   extend org.apache.struts.action.ActionForm
 • Most likely you will have already built model object such as
   Customer, Employee, etc…
 • Because you don’t want to tie your existing model objects to the
   Struts framework by having to extend ActionForm, Struts
   provides a org.apache.struts.util.PropertyUtils class that has a
   static method called copyProperties
 • When your controller receives a form, it can simply call
   PropertyUtils.copyProperties(myModel, form) to copy all form
   properties to your original model object.




Feb 11, 2003          Introduction to Jakarta Struts -
                            Gyanendra Dwivedi
Model: ActionForm
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import org.apache.struts.action.ActionForm;
  import org.apache.struts.action.ActionMapping;
  import org.apache.struts.upload.FormFile;

  public class LogonForm extends ActionForm {
  protected String userName;
  protected String password;

  public void setUserName(String userName) {
  this.userName = userName;
  }
  public void setPassword(String password) {
  this.password = password;
  }
  //There would also be getters for these properties
  }



Feb 11, 2003              Introduction to Jakarta Struts -
                                Gyanendra Dwivedi
Model: Action Form (cont…)
 • When this “LogonForm” is associated with a controller, it will be
   passed to the controller whenever it’s service is requested by the
   user.
 • JSP pages acting as the view for this LogonForm are
   automatically updated by Struts with the current values of the
   UserName and Password properties.
 • If the user changes the properties via the JSP page, the
   LogonForm will automatically be updated by Struts
 • But what if the user screws up and enters invalid data?
   ActionForms provide validation…
 • Before an ActionForm object is passed to a controller for
   processing, a “validate” method can be implemented on the form
   which allows the form to belay processing until the user fixes
   invalid input as we will see on the next slide...


Feb 11, 2003           Introduction to Jakarta Struts -
                             Gyanendra Dwivedi
Model: ActionForm Validation
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
if (“”.equals(this.userName)) {
ActionErrors aes = new ActionErrors();
aes.add(new ActionError(“error.username.invalid”));
return aes;
}
}



Typically what will happen is Struts will see that errors are being returned
and will forward the user to a jsp page that has been setup as the “failure”
page.
Usually, the errors result from bad input on a form, so the failure page will
be set to the original form and any <html:errors> tags which are found are
replaced with the contents of the ActionErrors returned from the validate
method.
  Feb 11, 2003             Introduction to Jakarta Struts -
                                 Gyanendra Dwivedi
The Controller
 • The controller is the switch board of MVC.
 • It directs the user to the appropriate views by providing the view
   with the correct model
 • The task of directing users to appropriate views is called
   “mapping” in struts.
 • Luckily, the Struts framework provides a base object called
   org.apache.struts.action.ActionServlet.
 • The ActionServlet class uses a configuration file called struts-
   config.xml to read mapping data called action mappings
 • The ActionServlet class reads the incoming URI and tries to
   match the URI against a set of action mappings to see if it can
   find a controller class which would be willing to handle the
   request
 • This process is described in a diagram on the following page


Feb 11, 2003            Introduction to Jakarta Struts -
                              Gyanendra Dwivedi
Controller (cont…)
http://myhost/authorize.do



Server configured to pass *.do extensions to
org.apache.struts.action.ActionServlet
via a web.xml configuration file


ActionServlet object inspects the URI and tries to match it
against an ActionMapping located in the struts-config.xml file.



Instance of appropriate Action class is found and it’s perform() method is
called

 Action object handles the request and returns control to a view based where the user is within
 the flow of the application

Feb 11, 2003                    Introduction to Jakarta Struts -
                                      Gyanendra Dwivedi
Controller: Sample
public class LogonAction extends Action {

public ActionForward perform(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
LogonForm myForm = (LogonForm) form;

if (myForm.getUserName().equals(“john”) &&
myForm.getPassword().equals(“doe”)) {
//return a forward to our success page
return mapping.findForward(”success”);
} else {
ActionErrors errors = new ActionErrors();
errors.add("password",
new ActionError("error.password.required"));
this.saveErrors(errors); //Action implements this method
//go back to the page that made the request
return (new ActionForward(mapping.getInput()));
}

}
}




    Feb 11, 2003                        Introduction to Jakarta Struts -
                                              Gyanendra Dwivedi
Controller: Forwards
 • You might be wondering what mapping.findForward(“success”)
   means?
     o The mapping object passed to the Controller’s perform() method is
       of type ActionMapping.
     o When you setup your struts-config.xml file you can define forward
       tags that are available via the ActionMapping.findForward() method.
     o In the previous example, our ActionMapping object would have
       been loaded with values from the <action-mapping> section defined
       for the LogonAction controller in struts-config.xml.




Feb 11, 2003             Introduction to Jakarta Struts -
                               Gyanendra Dwivedi
Controller: ActionMapping

<action-mappings>
<action path="/logon"
type="org.apache.struts.example.LogonAction"
name="logonForm"
scope="request"
input="/logon.jsp">
</action>
<forward name="success” path="/msgBoard.jsp"/>
</action-mappings>



Feb 11, 2003     Introduction to Jakarta Struts -
                       Gyanendra Dwivedi
The View
    •   The view in Struts is             •   JSP solves this by introducing
        represented by JSP pages              the concept of Tag Libraries
    •   JSP pages allows developers to         o Taglibs allow web designers
        write java code, and access               the convenience of using
        server side java objects in a             HTML like tags
        web page                               o It lets developers program
    •   Although this is good, we will            the logic behind the tags
        distract ourselves from the            o The attributes of the tags are
        reason we are using Struts and            used as basic parameters
        MVC.                                      that the developers will
         o We want to let our web page            interpret, which could
            authors create dynamic web            change the output generated
            pages without knowing how             by the tag
            to program


* Struts contains a series of taglibs designed to allow developers and web page
authors the
ability to communication one Introduction tofacilitate dynamic web content
   Feb 11, 2003                another to Jakarta Struts -
                                Gyanendra Dwivedi
The View: Example
<%@ page language="java" %>                                                   <tr>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>                    <th align="right">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>                    <bean:message key="prompt.password"/>
                                                                              </th>
<html:html locale="true">                                                     <td align="left">
<head>                                                                        <html:password property="password"
<title><bean:message key="logon.title"/></title>                              size="16" maxlength="16"/>
<html:base/>                                                                  </td>
</head>                                                                       </tr>
<body bgcolor="white">
                                                                              <tr>
<html:errors/>                                                                <td align="right">
                                                                              <html:submit property="submit"
<html:form action="/logon.do" focus="username">                               value="Submit"/>
<table border="0" width="100%">                                               </td>
                                                                              <td align="left">
<tr>                                                                          <html:reset/>
<th align="right">                                                            </td>
<bean:message key="prompt.username"/>                                         </tr>
</th>
<td align="left">                                                             </table>
<html:text property="username" size="16" maxlength="16"/>
</td>                                                                         </html:form>
</tr>
                                                                              </body>
                                                                              </html:html>




    Feb 11, 2003                                   Introduction to Jakarta Struts -
                                                         Gyanendra Dwivedi
View: Internationalization
 • Commonly referred to as i18n (I <followed by 18 letters> n)
 • The ability to maintain a web app in several different languages
 • Based on the language setup on the client side, the web app will
   auto-magic-ally
 • This is achieve in Struts through Java Resource Bundles
 • ResourceBundles are classes that support, among other things,
   String data.
 • Instead of having to make a ResourceBundle class for each
   language supported by your web app, resource bundles can be
   described as text files
 • If you had a set of strings in the French language you might
   make a file named MyStrings_fr.properties




Feb 11, 2003           Introduction to Jakarta Struts -
                             Gyanendra Dwivedi
View: i18n (cont…)
 • When the resource bundle class loader tries to load
   MyStrings_fr, it will look for a MyStrings_fr.properties file and
   create the class based on the properties in the file
 • Part of the Struts framework states that when setting up the
   ActionServlet in the web.xml file, if you add an initialization
   parameter named “application” this should contain the class
   name of your resource file:
        <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>
        org.apache.struts.action.ActionServlet
        </servlet-class>
        <init-param>
        <param-name>application</param-name>
        <param-value>myPackage.MyResources</param-value>
        </init-param>
        </servlet>




Feb 11, 2003                   Introduction to Jakarta Struts -
                                     Gyanendra Dwivedi
View: i18n (cont…)
 • In the previous example, when the ActionServlet is loaded it will
   read it’s “application” parameter to figure out that it should load
   string resources from mypackage.MyResources
     o If it doesn’t find a class by that name, it tries to find a
       MyResources.properties file
     o It then figures out what language the client is using. If it is different
       from the default, it looks up the 2 character ISO language code and
       tries to look for a class or .properties file by appending the ISO code
       to the class:
           If the client is French it would look up:
                 1) mypackage.MyResources_fr.class
                 If it can’t find this class it then looks for:
                 2) mypackage.MyResources_fr.properties




Feb 11, 2003                   Introduction to Jakarta Struts -
                                     Gyanendra Dwivedi
View i18n (cont…)

MyResources.properties file: MyResources_fr.properties
                             file:
helloworld.title=Hello World!
menu.file=File                                   helloworld.title=Allô monde!
menu.file.open=Open                              menu.file=Dossier
menu.file.close=Close                            menu.file.open=Ouvrir
menu.file.exit=Exit                              menu.file.close=Fermer
menu.edit=Edit                                   menu.file.exit=Sortie
menu.edit.copy=Copy                              menu.edit=Rédiger
menu.edit.paste=Paste                            menu.edit.copy=Copier
                                                 menu.edit.paste=Pâte




  Feb 11, 2003                  Introduction to Jakarta Struts -
                                      Gyanendra Dwivedi
View i18n (cont…)
 • In order for web developers to get at the string resources we use
   a special Struts tag called <bean:message/>
 • e.g. <bean:message key=”helloworld.title"/>
     o   This tag will be replaced with text from the appropriate resource
         bundle associated with this web app (via the “application” init param
         for the ActionServlet in web.xml) for the key logon.title




Feb 11, 2003               Introduction to Jakarta Struts -
                                 Gyanendra Dwivedi
Resources
 • Struts homepage
     o   http://jakarta.apache.org/struts/
 • Sun’s Servlet Specification
     o   http://java.sun.com/products/servlet/download.html#specs
 • Sun’s JSP Specification
     o   http://java.sun.com/products/jsp/download.html
 • Blue Stone’s Struts Tutorial
     o   http://developer.bluestone.com/scripts/SaISAPI.dll/Gallery.class/de
         mos/trailMaps/index.jsp
 • My email address for questions:
     o   craiger@tataryn.net




Feb 11, 2003                Introduction to Jakarta Struts -
                                  Gyanendra Dwivedi

Mais conteúdo relacionado

Semelhante a 72185-26528-StrutsMVC

Krazykoder struts2 intro
Krazykoder struts2 introKrazykoder struts2 intro
Krazykoder struts2 intro
Krazy Koder
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
Long Nguyen
 

Semelhante a 72185-26528-StrutsMVC (20)

Struts framework
Struts frameworkStruts framework
Struts framework
 
Struts2
Struts2Struts2
Struts2
 
Struts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web ApplicationsStruts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web Applications
 
Struts Interceptors
Struts InterceptorsStruts Interceptors
Struts Interceptors
 
Struts
StrutsStruts
Struts
 
Struts Interview Questions
Struts Interview QuestionsStruts Interview Questions
Struts Interview Questions
 
Struts 1
Struts 1Struts 1
Struts 1
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Krazykoder struts2 intro
Krazykoder struts2 introKrazykoder struts2 intro
Krazykoder struts2 intro
 
Struts
StrutsStruts
Struts
 
Struts & spring framework issues
Struts & spring framework issuesStruts & spring framework issues
Struts & spring framework issues
 
Java and XPages
Java and XPagesJava and XPages
Java and XPages
 
Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC  Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC
 
Skillwise Struts.x
Skillwise Struts.xSkillwise Struts.x
Skillwise Struts.x
 
Struts 2 – Architecture
Struts 2 – ArchitectureStruts 2 – Architecture
Struts 2 – Architecture
 
Struts ppt 1
Struts ppt 1Struts ppt 1
Struts ppt 1
 
Struts2.x
Struts2.xStruts2.x
Struts2.x
 
Integration of Struts & Spring & Hibernate for Enterprise Applications
Integration of Struts & Spring & Hibernate for Enterprise ApplicationsIntegration of Struts & Spring & Hibernate for Enterprise Applications
Integration of Struts & Spring & Hibernate for Enterprise Applications
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts framework
 

Mais de Arjun Shanka (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
javarmi
javarmijavarmi
javarmi
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
hibernate
hibernatehibernate
hibernate
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
swingbasics
swingbasicsswingbasics
swingbasics
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
javabeans
javabeansjavabeans
javabeans
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
javaiostream
javaiostreamjavaiostream
javaiostream
 
servlets
servletsservlets
servlets
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

72185-26528-StrutsMVC

  • 1. Introduction to MVC and the Jakarta Struts Framework By Gyanendra Dwivedi Software Consultant
  • 2. What is MVC • The Model View Controller design pattern is a technique used to separate Business logic/state (the Model) from User Interface (the View) and program progression/flow (the Control). • This pattern is very useful when it comes to modern web development: o The majority of modern, high usage websites are dynamically driven. o People well skilled at presentation (HTML writers) seldom know how to develop back-end solutions and visa versa. o Separating business rules from presentation is good no matter what environment you develop in be it web or desktop. Feb 11, 2003 Introduction to Jakarta Struts – Gyanendra Dwivedi
  • 3. What is MVC (cont…) • The View o The view is how data is represented to the user. For instance the view in a web application may be an HTML page, an image or other media • The Model o The model represents the data in the system. For instance, a model might represent the properties associated with a user’s profile • The Controller o The controller is the glue between the model and the view. It is responsible for controlling the flow of the program as well as processing updates from the model to the view and visa versa Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 4. What is MVC (cont…) User View Controller Model Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 5. What is MVC (cont…) User View Controller Model Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 6. Benefits of MVC • Promotes Modularity • Multiple views • Abstraction • Allows application to be defined in a flow-chart, use-case or activity diagram which is more easily transferred to implementation. Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 7. Designing an MVC App. • Let’s try designing an application from scratch • The application will be a message board where users can view messages and post messages • The application will require that a user has an account setup with the message board before posting a message, but an account is not required for viewing a message. • The basic components we must implement for this message board are: o User profile o Logon/authentication o Message List o Message Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 8. Activity Diagrams • I find the UML activity diagrams to be the most useful construct for describing program flow. • Activity diagrams are much like flow charts, except a few new constructs are added such as describing concurrency as well as recursive elements. • Each node of the Activity Diagram can be thought of as a call to a “Controller” asking it to take you to the next step in the application Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 9. Activity Diagram: Create Profile Create Profile Create Edit Profile [invalid] == Profile() [else] Save Profile Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 10. Activity Diagram: Logon Login Form Create Profile() [new user] == Logon() [else] Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 11. Activity Diagram: View Msg. Show Msg. Board Select Select Msg. == Msg() Display Msg. Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 12. Activity Diagram: Edit Msg. Select Msg() Logon() [expired session] [else] Create New Msg. Edit Msg. [else] Save Msg. Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 13. Jakarta Struts • In order to take advantage of the MVC design pattern in your applications a considerable framework must be in place. • Today we are going to learn about such a framework named Struts • Struts is an open source MVC framework developed by the Apache Jakarta project group. • Struts allows JSP/Servlet writers the ability to fashion their web applications using the MVC design pattern. • By designing your web application using Struts you allow: o Architect the ability to design using the MVC pattern o Developer to exploit the Struts framework when building the app. o Web designer to be sheltered from learning how to program http://jakarta.apache.org/struts/ Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 14. Struts (cont…) • Struts takes the grunt work out of developing an MVC based web app. • The Struts framework provides a plethora of canned objects which can facilitate fundamental aspects of MVC, while allowing you to extend further as need suites • Struts allows you to configure a lot of the default framework objects through xml configuration files. • Our examples will use the Struts framework using the Apache Tomcat Servlet/JSP container. http://jakarta.apache.org/tomcat/ • Tomcat 3.2.1 provides a reference implementation of the Servlet specification 2.2 and JSP specification 1.1 Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 15. Struts (cont…) • The components of MVC in Struts: o The View is usually defined as a JSP or HTML page. o The Model is usually defined as a Java object (sometimes called a bean). o The Controller is defined by a Java object which extends the org.apache.struts.action.Action class. The Action class is at the heart of the Struts framework. Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 16. Struts: The Model • To define a model in Struts is simple. Just create a java class and provide some functions. • Your model classes should be coded independent of the Struts framework to promote maximum code reuse by other applications (i.e. if you have to reference javax.servlet.* class in your model, you are doing something wrong) • Struts provides some default Model components, the most important of which is ActionForm. • If you create a Model class by extending the Struts ActionForm class, Struts will o Ensure your form bean is created when needed o Ensure form submittal directly updates your form object with the inputted values o Your controller object will be passed the form bean Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 17. The Model (cont…) • Struts will only handle models in an automatic fashion if you extend org.apache.struts.action.ActionForm • Most likely you will have already built model object such as Customer, Employee, etc… • Because you don’t want to tie your existing model objects to the Struts framework by having to extend ActionForm, Struts provides a org.apache.struts.util.PropertyUtils class that has a static method called copyProperties • When your controller receives a form, it can simply call PropertyUtils.copyProperties(myModel, form) to copy all form properties to your original model object. Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 18. Model: ActionForm import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; public class LogonForm extends ActionForm { protected String userName; protected String password; public void setUserName(String userName) { this.userName = userName; } public void setPassword(String password) { this.password = password; } //There would also be getters for these properties } Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 19. Model: Action Form (cont…) • When this “LogonForm” is associated with a controller, it will be passed to the controller whenever it’s service is requested by the user. • JSP pages acting as the view for this LogonForm are automatically updated by Struts with the current values of the UserName and Password properties. • If the user changes the properties via the JSP page, the LogonForm will automatically be updated by Struts • But what if the user screws up and enters invalid data? ActionForms provide validation… • Before an ActionForm object is passed to a controller for processing, a “validate” method can be implemented on the form which allows the form to belay processing until the user fixes invalid input as we will see on the next slide... Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 20. Model: ActionForm Validation public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { if (“”.equals(this.userName)) { ActionErrors aes = new ActionErrors(); aes.add(new ActionError(“error.username.invalid”)); return aes; } } Typically what will happen is Struts will see that errors are being returned and will forward the user to a jsp page that has been setup as the “failure” page. Usually, the errors result from bad input on a form, so the failure page will be set to the original form and any <html:errors> tags which are found are replaced with the contents of the ActionErrors returned from the validate method. Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 21. The Controller • The controller is the switch board of MVC. • It directs the user to the appropriate views by providing the view with the correct model • The task of directing users to appropriate views is called “mapping” in struts. • Luckily, the Struts framework provides a base object called org.apache.struts.action.ActionServlet. • The ActionServlet class uses a configuration file called struts- config.xml to read mapping data called action mappings • The ActionServlet class reads the incoming URI and tries to match the URI against a set of action mappings to see if it can find a controller class which would be willing to handle the request • This process is described in a diagram on the following page Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 22. Controller (cont…) http://myhost/authorize.do Server configured to pass *.do extensions to org.apache.struts.action.ActionServlet via a web.xml configuration file ActionServlet object inspects the URI and tries to match it against an ActionMapping located in the struts-config.xml file. Instance of appropriate Action class is found and it’s perform() method is called Action object handles the request and returns control to a view based where the user is within the flow of the application Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 23. Controller: Sample public class LogonAction extends Action { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { LogonForm myForm = (LogonForm) form; if (myForm.getUserName().equals(“john”) && myForm.getPassword().equals(“doe”)) { //return a forward to our success page return mapping.findForward(”success”); } else { ActionErrors errors = new ActionErrors(); errors.add("password", new ActionError("error.password.required")); this.saveErrors(errors); //Action implements this method //go back to the page that made the request return (new ActionForward(mapping.getInput())); } } } Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 24. Controller: Forwards • You might be wondering what mapping.findForward(“success”) means? o The mapping object passed to the Controller’s perform() method is of type ActionMapping. o When you setup your struts-config.xml file you can define forward tags that are available via the ActionMapping.findForward() method. o In the previous example, our ActionMapping object would have been loaded with values from the <action-mapping> section defined for the LogonAction controller in struts-config.xml. Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 25. Controller: ActionMapping <action-mappings> <action path="/logon" type="org.apache.struts.example.LogonAction" name="logonForm" scope="request" input="/logon.jsp"> </action> <forward name="success” path="/msgBoard.jsp"/> </action-mappings> Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 26. The View • The view in Struts is • JSP solves this by introducing represented by JSP pages the concept of Tag Libraries • JSP pages allows developers to o Taglibs allow web designers write java code, and access the convenience of using server side java objects in a HTML like tags web page o It lets developers program • Although this is good, we will the logic behind the tags distract ourselves from the o The attributes of the tags are reason we are using Struts and used as basic parameters MVC. that the developers will o We want to let our web page interpret, which could authors create dynamic web change the output generated pages without knowing how by the tag to program * Struts contains a series of taglibs designed to allow developers and web page authors the ability to communication one Introduction tofacilitate dynamic web content Feb 11, 2003 another to Jakarta Struts - Gyanendra Dwivedi
  • 27. The View: Example <%@ page language="java" %> <tr> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <th align="right"> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <bean:message key="prompt.password"/> </th> <html:html locale="true"> <td align="left"> <head> <html:password property="password" <title><bean:message key="logon.title"/></title> size="16" maxlength="16"/> <html:base/> </td> </head> </tr> <body bgcolor="white"> <tr> <html:errors/> <td align="right"> <html:submit property="submit" <html:form action="/logon.do" focus="username"> value="Submit"/> <table border="0" width="100%"> </td> <td align="left"> <tr> <html:reset/> <th align="right"> </td> <bean:message key="prompt.username"/> </tr> </th> <td align="left"> </table> <html:text property="username" size="16" maxlength="16"/> </td> </html:form> </tr> </body> </html:html> Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 28. View: Internationalization • Commonly referred to as i18n (I <followed by 18 letters> n) • The ability to maintain a web app in several different languages • Based on the language setup on the client side, the web app will auto-magic-ally • This is achieve in Struts through Java Resource Bundles • ResourceBundles are classes that support, among other things, String data. • Instead of having to make a ResourceBundle class for each language supported by your web app, resource bundles can be described as text files • If you had a set of strings in the French language you might make a file named MyStrings_fr.properties Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 29. View: i18n (cont…) • When the resource bundle class loader tries to load MyStrings_fr, it will look for a MyStrings_fr.properties file and create the class based on the properties in the file • Part of the Struts framework states that when setting up the ActionServlet in the web.xml file, if you add an initialization parameter named “application” this should contain the class name of your resource file: <servlet> <servlet-name>action</servlet-name> <servlet-class> org.apache.struts.action.ActionServlet </servlet-class> <init-param> <param-name>application</param-name> <param-value>myPackage.MyResources</param-value> </init-param> </servlet> Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 30. View: i18n (cont…) • In the previous example, when the ActionServlet is loaded it will read it’s “application” parameter to figure out that it should load string resources from mypackage.MyResources o If it doesn’t find a class by that name, it tries to find a MyResources.properties file o It then figures out what language the client is using. If it is different from the default, it looks up the 2 character ISO language code and tries to look for a class or .properties file by appending the ISO code to the class:  If the client is French it would look up: 1) mypackage.MyResources_fr.class If it can’t find this class it then looks for: 2) mypackage.MyResources_fr.properties Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 31. View i18n (cont…) MyResources.properties file: MyResources_fr.properties file: helloworld.title=Hello World! menu.file=File helloworld.title=Allô monde! menu.file.open=Open menu.file=Dossier menu.file.close=Close menu.file.open=Ouvrir menu.file.exit=Exit menu.file.close=Fermer menu.edit=Edit menu.file.exit=Sortie menu.edit.copy=Copy menu.edit=Rédiger menu.edit.paste=Paste menu.edit.copy=Copier menu.edit.paste=Pâte Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 32. View i18n (cont…) • In order for web developers to get at the string resources we use a special Struts tag called <bean:message/> • e.g. <bean:message key=”helloworld.title"/> o This tag will be replaced with text from the appropriate resource bundle associated with this web app (via the “application” init param for the ActionServlet in web.xml) for the key logon.title Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi
  • 33. Resources • Struts homepage o http://jakarta.apache.org/struts/ • Sun’s Servlet Specification o http://java.sun.com/products/servlet/download.html#specs • Sun’s JSP Specification o http://java.sun.com/products/jsp/download.html • Blue Stone’s Struts Tutorial o http://developer.bluestone.com/scripts/SaISAPI.dll/Gallery.class/de mos/trailMaps/index.jsp • My email address for questions: o craiger@tataryn.net Feb 11, 2003 Introduction to Jakarta Struts - Gyanendra Dwivedi

Notas do Editor

  1. MVC promotes modularity by sperating business rules, from program flow and User interface. An important part of web applications is presenting different views of data. Although the views may be different, the Model (or data) would stay the same. This is the heart of MVC. (e.g. Stock Data in chart/numbered) Abstraction is another key point of MVC, it allows developers the ability to expose an API which shields from database changes or other implementation changes. Also, web developers don’t have to worry about how the underlying components work, just simply how to access them. Architects will like the fact that they can produce a Use case or Activity diagram and have their developers quickly institute the program flow they have mapped out.
  2. I like to think of an activity diagram as a web page. Each action state in the diagram can be thought of as a webpage along a certain trail. Some pages may have links to other trails, these links are called Activity states and they typically represent a separate activity diagram.
  3. Action States and Activity State.
  4. &lt;html:form action=“/logon.do” focus=“username”&gt; When the submit button is pressed, the input of this form is sent to logo.do. That is dispatched to the ActionServlet, which then looks up the mapping to the LogonAction object. &lt;html:text property=“username” …/&gt; This will look up the form object associated with this page and will display the value of that property in an html text input box.
  5. Go over example: web.xml: 1) database servlet, initializes a hashed database the is present throughout the application 2) Defines the action servlet and associates it with the .do extension. struts-config.xml: 1) Set’s up the form beans, name property for action==formbean name 2) Set’s up any global forwards 3) Actions: path is the URI which will tell the ActionServlet to pass the request to this controller type is the class name of the controller which services these requests name is the name of the form bean we setup to handle input scope