Apache Struts

  • Summary
    • Central controller mediates application flow
    • Controller delegates to appropriate handler
    • Handlers are tied to model components
    • Model encapsulates business logic
    • Control forwarded back through the controller to the appropriate view.
    • Controller bundles and routes HTTP request to other objects in framework
    • Controller parses configuration file
    • Configuration file contains action mappings (determines navigation)
    • Controller uses mappings to turn HTTP requests into application actions.
    • Mapping must specify
      • A request path
      • Object type to act upon the request.
    • ActionForm Beans
      • Extends the ActionForm class
      • Create one for each input form in the application
      • If defined in the Action Mapping configuration file, the controller servlet will perform the following.
        • Check session for instance of bean of appropriate class
        • If no session bean exists, one is created automaticall
        • For every request parameter whose name corresponds to the name of a property in the bean, the corresponding setter method will be called.
        • The updated ActionForm bean will be passed to the Action Class perform() method when it is called, making there values immediately available.
    • Business Logic Beans
      • Should encapsulate the functional logic of application as method calls on JavaBeans designed for this purpose.
      • For maximum code re-use, business logic beans should be designed & implemented so that they do not know they are being executed in a web application environment
      • For 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 calls.
  • Tiles: Tiles builds on the “include” feature provided by the JSP specification to provide a full-featured, robust framework for assembling presentation pages from component parts. Each part (“Tile”) can be reused as often as needed throughout your application.
    • Screen definitions
      • Create a screen by assembling Tiles , e.g. header, footer, menu, body
      • Definitions can take place:
        • in a centralized XML file
        • directly in JSP pages
        • in Struts Actions
      • Definitions provide an inheritance mechanism: a definition can extend another one and override some (or all) of its parameters
    • Layouts
      • Define common page layouts and reuse them across your web site
      • Define menu layouts and pass lists of items and links
      • Define a portal layout, use it by passing list of Tiles (pages) to show
      • Reuse existing layouts, or define your own ones
    • Dynamic page building
      • Tiles are gathered dynamically during page reload. It is possible to change any attributes: layout, list of Tiles in portal, list of menu items
    • Reuse of Tiles /Components
      • If well defined, a Tile can be reused in different locations
      • Dynamic attributes are used to parameterize Tiles
      • It is possible to define libraries of reusable Tiles
      • Build a page by assembling predefined components, give them appropriate parameters
    • Internationalization (I18N)
      • It is possible to load different Tiles according to the user’s Locale
      • A mechanism similar to Java properties files is used for definition files: you can have one definition file per Locale, the appropriate definition is loaded according to the current Locale
    • Multi-channels
      • It is possible to load different Tiles according to a key stored e.g. in session context
      • The key could hold e.g. user privileges, browser type, …
      • A mechanism similar to Java properties files is used for definition files: you can have one definition file per key, the appropriate definition is loaded according to the key
  • Evaluate various solutions per specified criteria
    Solution Page number Code repetition Layout control Coupling Complexity
    Basic * *** * *** *
    JSP include ** ** * ** *
    Tiles insert ** ** * ** *
    Splitting bodies *** ** ** ** **
    Templating tiles *** * *** * **
    Struts and Tiles ** * *** * ***
    Tiles inheritance ** * *** * ***
    Scale: High: *** Medium: ** Low: *
  • What configuration files are used in Struts?
    1. ApplicationResourcesl.properties
    2. struts-config.xml

    These two files are used to bridge the gap between the Controller and the Model.

  • What helpers in the form of JSP pages are provided in Struts framework?
    1. struts-html.tld
    2. struts-bean.tld
    3. struts-logic.tld
  • Is Struts efficient?
    1. The Struts is not only thread-safe but thread-dependent(instantiates each Action once and allows other requests to be threaded through the original object.
    2. ActionForm beans minimize subclass code and shorten subclass hierarchies
    3. The Struts tag libraries provide general-purpose functionality
    4. The Struts components are reusable by the application
    5. The Struts localization strategies reduce the need for redundant JSPs
    6. The Struts is designed with an open architecture–subclass available
    7. The Struts is lightweight (5 core packages, 5 tag libraries)
    8. The Struts is open source and well documented (code to be examined easily)
    9. The Struts is model neutral
  • What are the core classes of Struts?
    Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.
  • What is ActionServlet?
    The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.
  • How you will make available any Message Resources Definitions file to the Struts Framework Environment?
    Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through < message-resources /> tag.
    Example:
  • What is Action Class?
    The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.
  • What is ActionForm?
    An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.
  • What is Struts Validator Framework?
    Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.
    The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.
  • Give the Details of XML files used in Validator Framework?
    The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.
  • How you will display validation fail errors on jsp page?
    Following tag displays all the errors:
  • How you will enable front-end validation based on the xml in validation.xml?
    The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form “logonForm” as defined in the validation.xml file. The when added in the jsp file generates the client site validation script.
  • Handling Forms
    One of the common chores in Web applications is the handling of forms. The JSP mechanism of automatically populating the fields of a JavaBean with form post parameters goes a long way in reducing the tedious code that would otherwise have to be written. Struts has built on top of this mechanism to provide an easy way to handle populating beans in wizard-style interfaces and handling validation.When creating a Struts form you have the option of creating a Struts form bean. This is a regular JavaBean with typical accessors and mutators for the fields of the bean (and very little other code) that subclasses from the org.apache- .struts.action.ActionForm base class. Note that these beans should not connect to a database to populate themselves or provide a lot of other infrastructure code. They should be lightweight classes that basically encapsulate entity information. Other beans should handle persistence and other duties. In fact, it’s typical to have one bean that acts as a collection of the entities represented by a Struts form bean (like the ScheduleBean used in the Action class).One of the additional sections in the struts-config XML document allows you to declare a class as a form bean. A form-bean declaration allows you to specify a name for the form bean and map that to a specific class. In the action mapping section of the config file you can automatically associate a form bean with an action. Notice the “add” action in the config file. The additional “name” parameter allows you to specify a form bean to use with that action. Once you have a form bean associated with an action, Struts will perform the following services for you before invoking the action method:

    • Check the user’s session for an instance of the bean under the name specified in the struts-config file. If one doesn’t exist yet, Struts creates one and adds it to the user’s session.
    • For every request parameter that matches one of the setXXX methods of the bean, the appropriate set method will be called.
    • The updated ActionForm bean is passed to the Action as a parameter.
  • Controller Servlet
    Several initialization parameters are passed to the controller servlet. The first specifies where to find the struts-config.xml document. This is the mapping document used by the controller. The second parameter specifies the debug level – the higher the number, the more debugging information is sent to the servlet engine log file. The third parameter is the mapping value. This points to the class responsible for handling RequestActionMapping. Last, the load-on-startup tag ensures that the servlet engine loads the Struts controller as it starts up. This saves time on the first invocation of the servlet by preloading it in memory. The number passed here isn’t particularly important (unless you have some dependent startup classes that depend on the controller being in memory – if so, make sure the controller servlet has a lower number).The next entry in the WEB.XML file specifies how to let the servlet engine know that a Struts resource has been requested (as opposed to some other content from the Web site). There are two ways to handle this: prefix mapping or extension mapping. With prefix mapping, every resource that appears after a certain prefix will be sent to the Struts controller. This is the way that servlet engines specify that a servlet has been requested (the servlet resource always appears after a “/servlet” prefix).Extension mapping (which we’re using here) maps all resources with a particular extension to the Struts controller. This works fine as long as you pick an extension that doesn’t interfere with any other registered file type. In this case we’re mapping all requests that end with “.do” to the Struts controller. The “.do” extension is arbitrary (it implies that a resource will “do” something), but it’s the one used by all the Struts examples so it’s a bit of a Struts standard.

    The remaining additions to the WEB.XML file specify the locations of the .TLD files for the custom Struts tags. Obviously you have to list only the tag libraries you’re using for this application (although it doesn’t hurt to list all six).

    The next configuration item needed for the Web application is the struts-config.xml document. It contains all the mappings for the controller servlet. In other words, these are the names of the resources you can request from the Web application. To understand these mappings, a discussion of Struts actions is in order.

    A classic problem in software engineering is how to handle a large number of mutually exclusive choices gracefully. This same problem popped up earlier when we were talking about how to create a single point-of-entry controller. The naive approach creates a huge switch statement or a long cascading series of if?else statements. However, a design pattern called Command solves this problem nicely.

    The Command design pattern uses inheritance instead of decisions to handle the possibilities. Typically, the developer creates an abstract class with a method called “execute()”, which has no code. Then, all the different possible actions subclass the abstract class and add concrete code to the execute() method. The mapping then becomes the name of the class to instantiate. This pattern makes it easy to keep a list of all the commands (because they all have a common ancestor) and iterate through it. This is the pattern used by Struts to handle the request mappings.

    In Struts you never need to create a controller servlet – the Struts developers have already created it for you. Instead, you create subclasses of the Struts Action class (org.apache .struts.action.Action). These action subclasses map to a particular resource, and this is one of the items in the struts-config document.

    When a request comes into the controller servlet, it matches the name of the request (notice that the mapping name in the config file doesn’t include the struts-specific extension, in our case “.do”) and instantiates an instance of the appropriate action class. This means that the controller servlet never has to change to add new actions to the Web application. All that’s required is the new action classes and an updated config file. Your action class takes on the role of the controller in the traditional Model2 architecture. In other words, it creates the bean (or beans) necessary to do work, calls methods on them, adds them to a collection, then forwards them to the appropriate display resource (typically a JSP). Listing 3 shows a typical small Action subclass.
    This is the basic operation of a simple case in Struts. However, Struts provides even more services for handling forms, validation, and internationalization.

  • What is the difference between Struts 1.0 and Struts 1.1
    The new features added to Struts 1.1 are

    1. RequestProcessor class
    2. Method perform() replaced by execute() in Struts base Action Class
    3. Changes to web.xml and struts-config.xml
    4. Declarative exception handling
    5. Dynamic ActionForms
    6. Plug-ins
    7. Multiple Application Modules
    8. Nested Tags
    9. The Struts Validator
    10. Change to the ORO package
    11. Change to Commons logging
    12. Removal of Admin actions
    13. Deprecation of the GenericDataSource
  • Explain Struts navigation flow
    client requests a path that matches the Action URI pattern. The container passes the request to the ActionServlet. If this is a modular application, the ActionServlet selects the appropriate module. The ActionServlet looks up the mapping for the path. If the mapping specifies a form bean, the ActionServlet sees if there is one already or creates one. If a form bean is in play, the ActionServlet resets and populates it from the HTTP request. If the mapping has the validate property set to true, it calls validate on the form bean. If it fails, the servlet forwards to the path specified by the input property and this control flow ends. If the mapping specifies an Action type, it is reused if it already exists or instantiated. The Action?s perform or execute method is called and passed the instantiated form bean (or null). The Action may populate the form bean, call business objects, and do whatever else is needed. The Action returns an ActionForward to the ActionServlet. If the ActionForward is to another Action URI, we begin again; otherwise, it?s off to a display page or some other resource. Most often, it is a JSP, in which case Jasper, or the equivalent (not Struts), renders the page.
  • What is the difference between ActionForm and DynaActionForm
    In struts 1.0, action form is used to populate the html tags in jsp using struts custom tag.when the java code changes, the change in action class is needed. To avoid the chages in struts 1.1 dyna action form is introduced.This can be used to develop using xml.The dyna action form bloats up with the struts-config.xml based definetion.
  • What is DispatchAction
    The DispatchAction class is used to group related actions into one class. DispatchAction is an abstract class, so
    you must override it to use it. It extends the Action class.
    It should be noted that you dont have to use the DispatchAction to group multiple actions into one Action class.
    You could just use a hidden field that you inspect to delegate to member() methods inside of your action.
  • How to call ejb from Struts
    use the Service Locator patter to look up the ejbs.
    OR
    You can use InitialContext and get the home interface.
  • What are the various Struts tag libraries
    struts-html tag library – used for creating dynamic HTML user interfaces and forms. struts-bean tag library – provides substantial enhancements to the basic capability provided by . struts-logic tag library – can manage conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management. struts-template tag library – contains tags that are useful in creating dynamic JSP templates for pages which share a common format.
  • What is the difference between ActionErrors and ActionMessages
    The difference between the classes is zero — all behavior in ActionErrors was pushed up into ActionMessages and all behavior in ActionError was pushed up into ActionMessage. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — errors being only one kind of message
  • How you will save the data across different pages for a particular client request using Struts
    If the request has a Form object, the data may be passed on through the Form object across pages. Or within the Action class, call request.getSession and use session.setAttribute(), though that will persist through the life of the session until altered.

Summary Central controller mediates application flow Controller delegates to appropriate handler Handlers are tied to model components Model encapsulates business logic Control forwarded back through the controller to the appropriate view. Controller bundles and routes HTTP request to other objects in framework Controller parses configuration file Configuration file contains action mappings (determines navigation) Controller uses…

Leave a Reply

Your email address will not be published. Required fields are marked *