1 / 202

Struts

Struts. An Open-source Architecture for Web Applications Facilitator: Tripti Shukla. Agenda . Why should you use Struts Installing Struts Struts Concepts What is MVC Configuring Struts Tag libraries Build a practical example What do you do when things go wrong? Advanced Topics.

Download Presentation

Struts

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Struts An Open-source Architecture forWeb Applications Facilitator: Tripti Shukla

  2. Agenda • Why should you use Struts • Installing Struts • Struts Concepts • What is MVC • Configuring Struts • Tag libraries • Build a practical example • What do you do when things go wrong? • Advanced Topics

  3. Struts Overview

  4. Frameworks in general • Provide a reusable structure: • may serve as a foundation for new products • re-usable semi-complete application • specialize to produce custom application

  5. Model 1 Framework • JSP combines the roles of the view and controller components • JSP page alone is responsible for processing the incoming request and replying back to the client • There is still separation of presentation from content, because all data access is performed using beans • Model 1 architecture is perfectly suitable for simple applications but it may not be desirable for complex implementations • Indiscriminate usage of this architecture usually leads to a significant amount of scriptlets or Java code embedded within the JSP page

  6. Drawbacks of JSP

  7. • Interweaving scriptlets and HTML results in hard to read and hard to maintain applications. • Writing code in JSPs diminishes the opportunity to reuse the code. Of course, you can put all Java methods in a JSP and include this page from other JSPs that need to use the methods. However, by doing so you're moving away from the object-oriented paradigm. For one thing, you will lose the power of inheritance. • It is harder to write Java code in a JSP than to do it in a Java class. Let's face it, your IDE is designed to analyze Java code in Java classes, not in JSPs. • It is easier to debug code if it is in a Java class. • It is easier to test business logic that is encapsulated in a Java class. • Java code in Java classes is easier to refactor.

  8. Model 2 Framework • JSP & Servlets work together in web applications • Servlets handle data access & control flow • JSP focus on tasks of writing HTML • Model • contains the core of the application's functionality i.e. business domain • encapsulates the state of the application

  9. Model 2 Framework • View • handles the presentation of the business domain • can access the model getters, but it has no knowledge of the setters • knows nothing about the controller • Controller • processes the user input to direct the flow and manage user state • reacts to the user input • creates and sets the model.

  10. Classic MVC Pattern • Controller mediates application flow • Model encapsulates business logic & data • View contains presentation logic

  11. Struts Framework Characteristics • Open source hosted by Apache Based on standard Java/J2EE technologies. • Core of struts is flexible controller layer • Struts encourages Model 2 application architecture • Model View Controller separates responsibilities • Struts is a Servlet that supports your applications • JSP Pages are also Servlets • Struts provides a pluggable framework • Tools exist to simplify Struts development

  12. Struts – on Model 2, MVC • Struts framework based on Model 2 architecture • Controller servlet manages flow between JSP pages • Special classes help with data access • Substantial tag library for JSP pages makes framework easy to use • MVC pattern implementation • ActionForwards & ActionMappings keep control flow decisions out of the presentation layer

  13. Struts • Client browser • An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response. • Controller • The Controller receives the request from the browser, and makes the decision where to send the request. • With Struts, the Controller is a command design pattern implemented as a servlet. • The struts-config.xml file configures the Controller.

  14. Struts • Business logic • The business logic updates the state of the model and helps control the flow of the application. • With Struts this is done with an Action class as a thin wrapper to the actual business logic. • Model state • The model represents the state of the application. • The business objects update the application state. • The ActionForm bean represents the Model state at a session or request level, and not at a persistent level. • The JSP file reads information from the ActionForm bean using JSP tags.

  15. Struts • View • The view is simply a JSP file. • There is no flow logic, no business logic, and no model information -- just tags. • Tags are one of the things that make Struts unique compared to other frameworks.

  16. Benefits • Configuration via XML files • Many changes can be made without modifying or recompiling Java code • Pages are loosely coupled; URLs not hardcoded • Form beans • Greatly simplifies processing of request parameters • HTML tags • Lets you get initial values from Java objects • Lets you redisplay forms with previous values intact • Form field validation • Client-side and server-side

  17. Benefits • Consistent implementation • Encourages consistent use of MVC throughout applications which employ JSP • Internationalization and Localization • Eg. en-us, en-ca, fr-ca • Supported through “resources” • Usually just a “properties” file i.e. resources.properties

  18. When to use Struts • In case of a very simple application, with a handful of pages, then you might consider a "Model 1" solution that uses only server pages. • With complicated application, with dozens of pages, that need to be maintained over time, then Struts can help

  19. Struts – Schematic Overview

  20. Core Struts Classes RELY-ON SOLUTIONS

  21. Core Struts Classes • ActionMapping Maps a path attribute to that of an incoming URI • ActionForward Encapsulates the destination of where to send control upon completion of the Action The destination is detailed in the configuration file: HTML,JSP, servlets

  22. Core Struts Classes • ActionForm • Hold state and behavior for user input using corresponding fields from the HttpServletRequest • No more request.getParameter() calls. For instance,the Struts framework will take fname from request stream and call UserActionForm.setFname() • Can be used to validate presentation data • Should be used to encapsulate data that is for delivery to the data model

  23. Core Struts Classes • ActionForm • is an abstract class that is sub-classed for each input form model • represents a general concept of data that is set or updated by a HTML form. E.g., you may have a UserActionForm that is set by an HTML Form • Also conducts form state validation • can be maintained at a session level

  24. Core Struts Classes • ActionServlet • responsible for packaging and routing HTTP traffic to the appropriate handler • takes on administering the behavior of the “Controller” • configured via the deployment descriptor of the web application and is typically is configured in the deployment descriptor to accept a pattern of URLs such as *.do • uses a configuration file so values are not hard-coded • Java developer does not need to recompile code when making flow changes

  25. Core Struts Classes • Action Classes The RequestProcessor delegate the work to be done to an Action.Provides loose coupling between the user request and the business • RequestProcessor • Takes on the behavior of the “Controller” by handling the core processing logic • Determine the ActionMapping associated with the request and instantiates the Action • Instantiates ActionForm if needed • Processes the ActionForward

  26. Components

  27. Struts Controller • Controller responsibilities include receiving input from a client, invoking a business operation, and coordinating the view to return back to the client. Of course, there are many other functions that the controller may perform, but these are a few of the primary ones. • JSP Model 2 architecture, on which Struts was fashioned the controller was implemented by a Java Servlet.

  28. Struts Controller • This servlet becomes the centralized point of control for the web application. • The controller servlet maps user actions into business operations and then helps to select the view to return to the client based on the request and other state information .

  29. Struts Controller

  30. Struts Controller In the Struts framework, the controller responsibilities are implemented by several different components, one of which is an instance of the org.apache.struts.action.ActionServlet

  31. Action Servlet • The ActionServlet extends the javax.servlet.http.HttpServlet class and is responsible for packaging and routing HTTP traffic to the appropriate handler in the framework. • The ActionServlet class is not abstract and therefore can be used as a concrete controller by your applications. • Prior to version 1.3 of the Struts framework, the ActionServlet was solely responsible for receiving the request and processing it by calling the appropriate handler.

  32. Action Servlet • In version 1.3, a new class called org.apache.struts.action.RequestProcessor has been introduced to process the request for the controller. • Like any other Java servlet, the Struts ActionServlet must be configured in the deployment descriptor for the web application i.e. web.xml. • Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation that is associated with the requested action.

  33. Action Class • An org.apache.struts.action.Action class in the Struts framework is an extension of the controller component. • The Action class decouples the client request from the business model. This decoupling allows for more than a one-to-one mapping between the user request and an Action class. • The Action class can perform other functions, such as authorization, logging, and session validation, before invoking the business operation .

  34. Action Class • The Struts Action class contains several methods, but the most important is the execute() method. public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException;

  35. Action Class • The execute() method is called on an instance of an Action class by the controller when a request is received from a client. • The controller will create an instance of the Action class if one doesn’t already exist. • The Struts framework will only create a single instance of each Action class in your application. • Since there is only one instance for all users, you must ensure that all of your Action classes operate properly in a multi-threaded environment.

  36. Action Class

  37. execute • Each one of the action classes that we’ll create for the application will extend the Struts Action class and override the execute method to carry out the specific operation. • it’s best to create an abstract base Action class for your application that all of your other action classes extend. • Always extend org.apache.struts.action.Action Class and implement execute() method.

  38. Mapping Action • At this point, you might be asking yourself, “How does the controller know which Action instance to invoke when it receives a request?” The answer is by inspecting the request information and utilizing a set of action mappings. • Action mappings are part of the Struts configuration information that is configured in a special XML file.

  39. Mapping Action • This configuration information is loaded into memory at startup and made available to the framework at runtime. • Each <action> element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class. The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.

  40. Mapping Action <action path="/login" type="com.test.struts.banking.action.LoginAction" scope="request" name="loginForm" validate="true" input="/login.jsp"> <forward name="Success" path="/action/getaccountinformation" redirect="true"/> <forward name="Failure" path="/login.jsp" redirect="true"/> </action>

  41. Mapping Action • The login action mapping shown here maps the path “/login” to the Action class com.test.struts.banking.LoginAction. • Whenever the controller receives a request where the path in the URI contains the string “/login”, the execute() method of the LoginAction instance will be invoked. • The Struts framework also uses the mappings to identify the resource to forward the user to once the action has completed .

  42. Determine Next View • How or what determines the view to return back to the client ? • If you looked closely at the execute() method signature in the Action class from the previous section, you might have noticed that the return type for the method is an org.apache.struts.action.ActionForward class.

  43. Determine Next View • The ActionForward class represents a destination to which the controller may send control once an Action has completed. • Instead of specifying an actual JSP page in the code, you can declaratively associate an action forward mapping with the JSP and then use that ActionForward throughout your application.

  44. forward • The action forwards are specified in the configuration file, similar to action mappings. They can be defined for a specific action as this forward is for the logout action mapping. <action path="/logout" type="com.test.struts.banking.action.LogoutAction" scope="request"> <forward name="Success" path="/login.jsp" redirect="true"/> </action>

  45. forward • The logout action declares a <forward> element that is named “Success”, which forwards to a resource of “/login.jsp”. Notice in this case, a redirect attribute is set to “true”. Instead of performing a forward using a RequestDispatcher, the request that invokes the logout action mapping will be redirected instead. • The action forward mappings can also be specified in a global section independent of any specific action mapping.

  46. Global-forward • The forwards defined in the global section are more general and don’t apply to a specific action. Notice that every forward must have a name and path, but the redirect flag is optional. If you don’t specify a redirect attribute, its default value is false and thus performs a forward. <global-forwards> <forward name="SystemFail" path="/systemerror.jsp" /> <forward name="SessionTimeOut" path="/sessiontimeout.jsp" /> </global-forwards>

  47. Struts Model Components

  48. Model Components • Using Model components to hide the implementation details for interacting with remote systems is one of the keys to using Struts effectively • ActionForm Beans • Represent actions that can change that state • Java Bean / EJBs • Represent internal state & business logic of the system • Relational Database Access • Struts can define the datasources for an application from within its standard configuration file

  49. ActionForm Beans • Create one for each input form in the application • Extends ActionForm class • May be defined in ActionMapping configuration file • Typically only has property getters & setters • Define property for each field present in the form • With associated getXXX() & setXXX() methods • Field name & property name must match • Place bean instance on form and use nested property references • If there’s a customer bean on the Action Form, then refer to the property “customer.name” in JSP • This would correspond to methods customer.getName() & customer.setName(String name) on customer bean

  50. ActionForm Beans • The struts-config.xml file controls which HTML form request maps to which ActionForm • Multiple requests can be mapped to an ActionForm • ActionForm can be mapped over multiple pages for things such as wizards

More Related