struts_ss

89
1 Introduction to Struts Framework

description

Struts tutorial

Transcript of struts_ss

  • *Introduction to Struts Framework

  • *

    STRUTS Objectives

    Overview of JSP Model 1 Architecture.Model-View-Controller (MVC) Architecture.What is Struts?Struts ComponentsModel ComponentsView ComponentsStruts Tag LibrariesApplication Resource FileError HandlingException HandlingValidator FrameworkTiles Framework

    Agenda

  • *JSP Model 1 Architecture

  • *JSP Model 1 ArchitectureModel 1 architecture is the easiest way of developing JSP based web application.

    The core part of Model 1 architecture is JSP and JavaBeans.

    Here, the client request is sent directly to the JSP page.

    The JSP contains embedded code and tags to access the JavaBeans.

    The JavaBeans holds the HTTP request parameters from the query string and connects to the middle tier or directly to the database for additional processing.

    The JSP page selects the next page for the client.

    No extra servlet involved in the process.

  • *Model 2 (MVC) Architecture

  • *MVC Design PatternThe MVC pattern separates responsibilities into three layers of functionality:

    Model: The data and business logic

    View: The presentation

    Controller: The flow control

    Each of these layers is loosely coupled to provide maximum flexibility with minimum effect on the other layers.

  • *

    MVC - ModelIn the MVC design pattern, the Model provides access to the necessary business data as well as the business logic needed to manipulate that data.

    The Model typically has some means to interact with persistent storage such as a database to retrieve, add, and update the data.

    The Model can be built up with Simple Java Beans or EJB or WebServices

  • *

    MVC - ControllerThe Controller handles all requests from the user and selects the view to return.

    When the Controller receives a request, the Controller forwards the request to the appropriate handler, which interprets what action to take based on the request.

    The Controller calls on the Model to perform the desired function.

    After the Model has performed the function, the Controller selects the View to send back to the user based on the state of the Models data.

  • *

    MVC - View

    The View is responsible for displaying data from the Model to the user.

    This layer also sends user data to the Controller.

    In the case of a Web application, this means that both the request and the response are in the domain of the View.

  • *

    Model2 (MVC) ArchitectureIn Model2 a controller, implemented as Servlet, is introduced to handle the user requests.

    In Model2 the user request is processed in the following steps after submission

    Controller Servlet handles the users request.Controller Servlet then instantiates appropriate Java Beans based on the request parameters.Java Beans communicates to the middle tier or directly to the database to fetch the required data.Controller then sets the resultant JavaBeans (same or new) in either, request, session or application context.Controller then dispatches the request to the next view based on the request URL.The View uses the resultant Java Beans to display data.

  • *

    Model2 (MVC) ArchitectureBrowser

    Servlet

    JSP

    JavaBeans

    Session EJB etc.Datastore1.1. Request6. Response4. Get result & set in scope2. Access Model & invoke Business LogicUses3. Connect to Database & get/save data5. Dispatch to next viewJ2EE Application Server

  • Advantages of MVC

    Greater flexibility: Its easy to add different View types (HTML, XML) and interchange varying data stores of the Model because of the clear separation of layers in the pattern.

    Best use of different skill sets: Designers can work on the View, programmers more familiar with data access can work on the Model, and others skilled in application development can work on the Controller. Differentiation of work is easier to accomplish because the layers are distinct.

    Ease of maintenance: The structure and flow of the application are clearly defined, making them easier to understand and modify. Parts are loosely coupled with each other.

    *

  • *What is Struts

  • *

    Struts advantages

    Struts is an open source created by Craig McClanahan & then donated to the Jakarta project of the Apache Software Foundation (ASF) in 2000 . In June 2001 struts 1.0 was released

    The Struts framework is a rich collection of Java libraries and can be broken down into the following major pieces - Base framework - Jsp tag libraries - Tiles plugin - Validator plugin

  • *

    MVC pattern as enforced in StrutsStruts provides a concrete implementation of the Controller part of the pattern.

    It also provides the connections between the Controller and Model layers and between the Controller and View layers,

    It doesnt insist on any particular View paradigm or does not requires the Model to be constructed in a particular way.

    Some of the components of Struts areActionServlet : The primary Controller classAction :: The handler classActionForm :: Holds the data of the user requeststruts-config.xml :: configuration file

  • *

    MVC pattern as enforced in Struts

  • *

    STRUTS A Framework

  • *Struts Components

  • *

    ActionServletThe central component of the Struts Controller is the ActionServlet.

    ActionServlet performs two important thingsOn startup it reads the Struts Configuration file and loads it into memory in the init() method.In doGet() or doPost() methods it intercepts HTTP request and handles the appropriately.The web.xml of the application should have ActionServlet declared using , along with appropriate servlet mappings using .

  • *

    A sample web.xml entry for ActionServlet

    action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml 1

    action *.do

  • *

    RequestProcessor

    After ActionServlet has intercepted the HTTP request, it delegates the request handling to RequestProcessor.

    The process() of the RequestProcessor does the following :

    The RequestProcessor first retreives the ActionMappings from struts-config.xml.From ActionMappings it gets the name of ActionForm and populates it if it is already created otherwise creates it first.Next if some validations are required on the input, that is doneLastly the execute() method of Action class is invoked.The RequestProcessor is specified in struts-config.xml as

  • *

    ActionMappings as shown in struts-config.xml

  • *

    ActionForm

    ActionForm is essentially a JavaBean with a list of private attributes and a pair of getXXX() and setXXX() method for each of the attributes.

    Struts application extends the ActionForm class to implement its own.

    RequestProcessor instantiates the ActionForms subclass and puts it in appropriate scope. Next RequestProcessor iterates through the HTTP request parameters and populates the matching attributes.

    Next if validation is enabled the validate() method is called.

  • *

    public class NameForm extends ActionForm{private String firstName;private String lastName;public String getFirstName(){return firstName;}public String getLastName() {return lastName;}public void setFirstName(String fName){firstName=fName;}public void setLastName(String lName){lastName=lName;}}

    ActionForm class

  • *

    STRUTS ActionForm Lifecycle

  • *

    ActionThe RequestProcessor instantiates the Action class specified in the ActionMapping and invokes the execute() method.

    The signature of execute() is

    public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception

    The execute() method should preferably contain only the presentation logic and no business logic.

    Putting business logic in execute() method limits the reuse of the business logic, which is not a very good design.

    This is an ideal starting point in the web layer to invoke the business logic.

  • *

    Action (contd)

    We should have our own class which extends the Action class

    public class NameAction extends Action {

    public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{NameForm nform = (NameForm) form;System.out.println(In NameAction ::execute());return mapping.findForward("success");}}

  • *

    ActionForward

    ActionForward is the class that encapsulates the next view information.ActionForward encapsulates the association of the logical name and the physical JSP page.The logical name and physical page is specified in the struts-config.xml file.

    After successful execution the execute() method of Acton class returns the appropriate ActionForward.

    return mapping.findForward("success");

    The ActionForward can be either local to one ActionMapping or global.

  • *

    struts-config.xml

    struts-config.xml is the primary configuration file for the Controller.

    Five important sections in struts-config.xml are:

    Form bean definition section Global forward definition section [optional]Action mapping definition sectionController configuration section [optional]Application Resources definition section. [optional]

  • *

    struts-config.xml

    Form bean definition section

    The form bean definition section contains one or more entries for each ActionForm.

    Each form bean is identified by an unique logical name.

    Type is the fully qualified class name of the ActionForm.

  • *struts-config.xmlAction mapping definition sectionThe ActionMapping section contains the mapping from URL path to an Action class and also associates a Form bean with the path.The attributes and elements of ActionMapping are:Attribute/ElementDescriptionPathThe URL pathTypeThe Action class name.NameThe logical name of the Form beanScopeScope of the Form bean ValidateIf true the form bean is validatedInputThe page to which the control will be forwarded in case of an error.ForwardThe physical page/another ActionMapping to which the control should be forwarded when ActionForward with this name is selected in the execute method of the Action class.

  • *

  • *

    struts-config.xmlGlobal forward definition sectionUnlike, local forwards Global Forward section is accessible from any ActionMapping.

  • *Model Components

  • *

    STRUTS Model Components

    Business Logic Beans Should encapsulate the functional logic of your application as method calls on JavaBeans designed for this purposeFor small to medium sized applications, business logic beans might be ordinary JavaBeans that interact with system state beans passed as arguments, or ordinary JavaBeans that access a database using JDBC callsFor larger applications, these beans will often be stateful or stateless Enterprise JavaBeans (EJBs)

  • *View Components

  • *

    STRUTS View ComponentsStruts framework does not provide JSPs.

    It provides JSP Custom Tag libraries which can be used in JSPs.

    First Name

    Second Name

  • *STRUTS Tag Libraries

  • *

    STRUTS Tag LibrariesHTML Tags Used to generate HTML forms that interact with the Struts APIsBean Tags Used to work with Java bean objects in JSPs , such as accessing bean values .Logic Tags Used to cleanly implement simple conditional logic in JSPs

  • *

    HTML Tags

    The tags in the Struts HTML library form a bridge between a JSP view and the other components of a Web application.

    Consequently, the majority of the HTML tags involve HTML forms.

    .

    The JSP file should inlcude the TLD files for this::

    The web.xml should inlcude

    /WEB-INF/struts-bean /WEB-INF/struts-bean.tld /WEB-INF/struts-html /WEB-INF/struts-html.tld

  • *

    HTML tags allows the usage of relative URL instead of abosolute URLs.

    The page context root is declared with the tag.

    An sample would be like

    Now all URLs not starting with / are assumed to be relative to the base href.

  • *

    HTML Tags tag generates the HTML representation of the Form.

    It has one mandatory attribute action.

    The action attribute represents the ActionMapping for this form.

    A sample

    It reads the ActionMapping in strust-config.xml and generates an HTML equivalent as

  • *

    HTML tags , tag generates the HTML representation of the text box.

    It has one mandatory attribute called property.

    The value of the property should exactly match with the attribute name specified in the Formbean.

    generates equivalent code for the submit button in HTML>

  • *

    HTML Tags Typical HTML Form

    First Name Street Address

  • *

    HTML Tags Typical Struts Form

  • *

    Bean Tags

  • *Logic TagsThe Logic tag library contains tags that are useful in managing conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management.

  • *Logic Tags

  • *Logic Tags - Example

    Emp IdFirst Name

  • *

    STRUTS View ComponentsBuilding Forms with StrutsThe taglib directive tells the JSP page compiler where to find the tag library descriptor for the Struts tag libraryThe errors tag displays any error messages that have been stored by a business logic component, or nothing if no errors have been stored

  • *

    STRUTS View Components

    Building Forms with Struts continuedThe form tag renders an HTML element, based on the specified attributesThe form tag also associates all of the fields within this form with a request scoped FormBean that is stored under the key FormNameThe form bean can also be specified in the Struts configuration file, in which case the Name and Type can be omitted hereThe text tag renders an HTML element of type "textThe submit and reset tags generate the corresponding buttons at the bottom of the form

  • *

    STRUTS View Components

    Input field types supportedcheckboxeshidden fieldspassword input fieldsradio buttonsreset buttonsselect listsoptionssubmit buttonstext input fieldstextareas

  • *

    STRUTS View Components

    Useful Presentation Tags[logic] iterate repeats its tag body once for each element of a specified collection (which can be an Enumeration, a Hashtable, a Vector, or an array of objects)[logic] present depending on which attribute is specified, this tag checks the current request, and evaluates the nested body content of this tag only if the specified value is present[logic] notPresent the companion tag to present, notPresent provides the same functionality when the specified attribute is not present

  • *

    STRUTS View ComponentsAutomatic Form ValidationStruts offers an additional facility to validate the input fields it has receivedTo utilize this feature, override the validate() method in your ActionForm classThe validate() method is called by the controller servlet after the bean properties have been populated, but before the corresponding action class's perform() method is invoked

  • *Application Resource File

  • *

    Application Resource FileThe Application Resource File stores the pre-defined messages to be shown in the JSP pages.

    Application Resource files normally has an extension as .properties and are stored in /WEB-INF/classes/

    It also needs to be declared in the struts-config.xml as

    Where, app1 is the respective package name and App1Messages.properties is the file name.

  • *

    ApplicationResources.propertiesprompt.firstName = First Nameprompt.lastName = Last Name

    button.save = Save Mebutton.cancel = Cancel Me

    errors.header=Validation ErrorPlz rectify the following error:errors.footer=

    error.firstName.null = First Name is required

  • *

    Modified JSP file

  • *Handling Errors

  • *

    validate() method in ActionFormStruts provides validate() method in the ActionForm to deal with input validations.

    The validate() method gets populated just after the Form bean is populated.

    A sample validate() method looks like

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){ ..}

    If errors are found then the validate() method returns ActionErrors object which holds the error.

    The generated erros are rendered in the JSP page using the tag.

  • *

    validate() methodpublic ActionErrors validate(ActionMapping mapping, HttpServletRequest request){ActionErrors errors = new ActionErrors();

    if(firstName == null || firstName.trim().equals("")) {errors.add("firstName",new ActionError("error.firstName.null"));}return errors;}

  • *Exception Handling

  • *Struts supports two types of Exception Handling

    DeclarativeProgrammatic

    STRUTS Exception Handling

  • *Declarative exception handlingAn application's exception-handling policies, including which exceptions are thrown and how they are to be handled, are maintained in a separate file (typically using XML)The XML file is completely external to the application codeThis approach makes it easier to modify the exception-handling logic without major recompilation of the code.

    STRUTS Exception Handling

  • *

    Sample Struts configuration file for declarative exception handling

    STRUTS Exception Handling

  • *

    STRUTS Exception Handling

  • *

    Sequence of EventsThe RequestProcessor class executes its processException() method.Finds the Exception in the action mappingThe default exception handler creates and stores an ActionError into the specified scope and gives the control to the resource specified in the path attribute

    STRUTS Exception Handling

  • *

    Programmatic Exception HandlingApplication specific exception handling in the code.Helps logging the Exception.Programmatically create and store ActionError into the appropriate scope and forward control to the appropriate ActionForward.

    STRUTS Exception Handling

  • *

    Sample code of Action Class handling Exception.

    try{// do something }catch (Exception exp) { //log the exception

    //Create and store the ActionError ActionErrors errs = new ActionErrors();

    STRUTS Exception Handling

  • * ActionError newEr = new ActionError(exp.getErrorCode(),exp.getArgs()); errs.add(ActionErrors.GLOBAL_ERROR,newEr); saveErrors(request, errs); //Return an ActionForward for the failure resource. return mapping.findForward(failure); }

    STRUTS Exception Handling

  • *Validator Framework

  • *

    Need for a Validation FrameworkValidator Framework allows you to move all the validation logic completely outside of the ActionForm.Declaratively configure all the validations for an application through external XML files.No validation logic is necessary in the ActionForm, which makes your application easier to develop and maintain.It provides many standard built-in validations

    STRUTS Validator Framework

  • *

    STRUTS Validator Framework

    Required jar files under WEB-INF/libCommons-validator.jarJakarta-oro.jar

    Two important config filesValidation-rules.xmlValidation.xml

  • *

    Validation-rules.xml

    STRUTS Validator Framework

  • *

    The Validator element supports seven attributesnameclassnamemethodmethodParamsmsgdepends

    STRUTS Validator Framework

  • *

    The resource bundle should have the following default key-value pairs. errors.required={0} is required. errors.minlength={0} cannot be less than {1} characters. errors.maxlength={0} cannot be greater than {1} characters. errors.invalid={0} is invalid. errors.byte={0} must be a byte. errors.short={0} must be a short. errors.integer={0} must be an integer. errors.long={0} must be a long. errors.float={0} must be a float. errors.double={0} must be a double. errors.date={0} is not a date. errors.range={0} is not in the range {1} through {2}. errors.creditcard={0} is not a valid credit card number. errors.email={0} is an invalid email address

    STRUTS Validator Framework

  • *

    Validation.xmlThis file is application specificIt defines which validation rules from the validation-rules.xml are used by a particular ActionFormThe validation logic is associated with one or more ActionForm classes through this external file.

    STRUTS Validator Framework

  • *

    A sample validation.xml file

    phone ^\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})$

    STRUTS Validator Framework

  • *

  • *

    Using an ActionForm with the ValidatorThe standard ActionForm cannot be used in the validator framework.Use subclass of the ActionForm class that is specifically designed to work with the Validator frameworkUse DynaValidatorForm or ValidatorForm

    STRUTS Validator Framework

  • *

    Steps to use default Validator framework- A SummaryPut validation-rules.xml and validation.xml files under WEB-INFEdit validation.xml file according to the needPut the default key-value pairs in the application resource bundle file.Use DynaValidatorForm or ValidatorForm instead of the default ActionForm

    STRUTS Validator Framework

  • * The Tiles Framework

  • *

    Each tile is just a web page in its own right & theyll all be inserted where you want them.This model promotes reusability.If the only thing that changes between the 500 web pages on your site is the individuals pages body and you want to keep the header, footer and a navigation menu the same for each page , Tiles can help you a lot

    STRUTS The Tiles FrameworkMenuBodyFooterHeader

  • *

    Sample code for to implement Tiles Framework

  • *

    Need to plug in tiles-definitions.xml in struts-config.xml file

    . . . .

  • *Creating the Layout

    < tr>

  • *

    Struts Resources

    Struts Main Web Site http://struts.apache.org/index

    Struts Book Struts Essential Skills Steven Holzner Struts Complete Reference James Holmes , Schildt

    Struts User Guidehttp://jakarta.apache.org/struts/userGuide/index.html

    Various Struts Resourceshttp://jakarta.apache.org/struts/resources.html

  • *

    Questions

  • *

    Part of what needs to be understood at this point is the history of how this evolved. First, Servlets were created, and Java programmers said this is a good thing. Servlets are faster and more powerful than standard CGI, are portable, and infinitely extensible. However, everything wasnt perfect. The Java programmer had to programmatically create HTML from within their Servlets. This of course was tiresome and problematic. So Java Server Pages were created, and Java programmers said this is a good thing. As with anything new and wonderful, JSPs were misused. Too much code was put into the JSP. Some discipline was needed. In the object-oriented programming world, discipline is defined as design patterns. Using the JSP for the view component and Servlets as the controller component was deemed to be the appropriate approach. Thus, using the MVC design pattern was adopted. Note that the MVC design pattern had been around for a while in other object-oriented languages.

    The Struts project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC framework to the Java community. In July 2001, Struts 1.0 was released.

    Within a web-based application, JavaBeans can be stored in (and accessed from) a number of different collections of "attributes". Each collection has different rules for the lifetime of that collection, and the visibility of the beans stored there. Together, the rules defining lifetime and visibility are called the scope of those beans. The Java Server Pages (JSP) Specification defines scope choices using the above terms (with the equivalent Servlet API concept defined in parentheses):

    You should note that a "form", in the sense discussed here, does not necessarily correspond to a single JSP page in the user interface. It is common in many applications to have a "form" (from the user's perspective) that extends over multiple pages. Think, for example, of the wizard style user interface that is commonly used when installing new applications. Struts encourages you to define a single ActionForm bean that contains properties for all of the fields, no matter which page the field is actually displayed on. Likewise, the various pages of the same form should all be submitted to the same Action Class. If you follow these suggestions, the page designers can rearrange the fields among the various pages, often without requiring changes to the processing logic.

    When writing business logic beans, there should never be any reference to resources that are only available within a web application server environment. It would NOT be a good idea to pass something like the HttpServletRequest block to a business logic bean. This would limit the use of that business logic bean to only be used within a web project. The idea is to have the business logic bean available to ANY type of application.There are currently four taglibs that Struts is packaged with. The struts-bean taglib contains tags useful in accessing beans and their properties, as well as defining new beans (based on these accesses) that are accessible to the remainder of the page via scripting variables and page scope attributes. Convenient mechanisms to create new beans based on the value of request cookies, headers, and parameters are also provided. The struts-html taglib contains tags used to create struts input forms, as well as other tags generally useful in the creation of HTML-based user interfaces. The struts-logic taglib contains tags that are useful in managing conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management. The struts-template taglib contains tags that define a template mechanism.

    About the form tagThe Struts form tag outputs a standard HTML form tag, and also links the input form with a JavaBean subclassed from the Struts ActionForm object (see Javadoc). Each field in the form should correspond to a property of the form's bean. When a field and property correspond, the bean is first used to populate the form, and then to store the user's input when the form is submitted to the controller servlet.The name of the bean and its class can be specified as a property to the form tag, but may also be omitted. If omitted, the ActionMappings database (loaded from the struts-config.xml file) is consulted. If the current page is specified as the input property for an action, the name of the action is used. The type property for the bean is also then taken from the configuration, via a Form Bean definition.

    One important item to point out about HTML is that the developer has no control over the HTML tags. They only serve very specific purposes. The developer has to develop within those limitations. One of the major advantages of using tab libraries is that youre NOT constrained with those limitations.Notice the