Presentation is loading. Please wait.

Presentation is loading. Please wait.

Controlling an Application with Struts

Similar presentations


Presentation on theme: "Controlling an Application with Struts"— Presentation transcript:

1 Controlling an Application with Struts
Schedule: Topic Timing Lecture 90 minutes Practice 30 minutes Total 120 minutes

2 Objectives After completing this lesson, you should be able to do the following: Define the role of the controller in the MVC architecture Define page navigation in a Struts application Handle success and exception navigation Define the different ways of editing Struts configuration Objectives The controller is a vital part of a Model-View-Controller (MVC) application. This lesson describes how Struts is used as the controller in an application. You learn about Struts organization and components and discover how the Struts configuration file is used to identify these components and determine the flow of the application.

3 ADF Business Services Tier ADF Application Module
The Controller Client Tier Middle Tier EIS Tier Web Container ADF Business Services Tier Controller ADF Application Module ADF View Object ADF Entity Object Model Database The Controller The controller is the central point of a Struts application. It coordinates actions that occur between the client request and the model.

4 ADF Implements MVC Using the Struts Controller
JSP JSF ADF UIX Swing/ ADF JClient View Struts Controller ADF Model Model ADF Business Components Web Services EJB Session Beans JavaBeans/ Other Business Services ADF and Struts This diagram illustrates how the ADF architecture implements the Struts controller and interacts with different types of components in the view. It also shows that the ADF model layer that Oracle provides acts as a facade, allowing the use of different types of technology to implement data access and persistency concerns.

5 Purpose of a Controller
On a Web page, everything significant happens on submit or a link. A controller intercepts a request and dispatches it correctly. The source page does not have to know how to handle an event or where to go next. The handling code does not need to know what page to display in response. The controller separates the model and the view. Purpose of a Controller In the MVC design pattern, application flow is mediated by a central controller. The controller delegates requests—in most cases, HTTP requests—to an appropriate handler. The handlers are tied to a model, and each handler acts as an adapter between the request and the model. The model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the controller to the appropriate view. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the view and model, which makes applications significantly easier to create and maintain. Instructor Note Make sure to stress the importance of the controller intercepting all HTTP requests. This is the core of the controller concept.

6 Example: Page Flow Without a Controller
<a href="page2.jsp"> <a href="page1.jsp"> page1.jsp page2.jsp Example: Page Flow Without a Controller In a typical Web application, the navigation and control is coded into each of the pages in the application. This is usually in the form <a href="page1.jsp"> embedded in the page. You need a link to every page that the user needs to navigate to in the course of using your application.

7 Example: Page Flow Without a Controller
<a href="page2.jsp"> <a href="page1.jsp"> page1.jsp page2.jsp Example: Page Flow Without a Controller (continued) In the example, if the application requires an intermediate step to be inserted into the flow, each of the pages must be changed to accommodate the new page. page1a.jsp

8 Example: Page Flow Without a Controller
<a href="page2.jsp"> <a href="page1.jsp"> page1.jsp page2.jsp Example: Page Flow Without a Controller (continued) The links that are previously used are now invalid. page1a.jsp

9 Example: Page Flow Without a Controller
page1.jsp page2.jsp Example: Page Flow Without a Controller (continued) The new flow includes links to and from each of the pages. Adding this page requires making changes to each of the pages in the flow. <a href="page1a.jsp"> <a href="page1a.jsp"> page1a.jsp

10 Example: Page Flow with a Controller
Next Previous page1.jsp page2.jsp Example: Page Flow with a Controller Now, for the same example, use a controller for managing page flow and navigation.

11 Example: Page Flow with a Controller
Next Previous Next Previous page1.jsp page2.jsp Example: Page Flow with a Controller (continued) When the new page is added to the flow, none of the pages need to be changed. The code to tell which page is next is within the controller. The controller manages all the page flow and navigation, so the pages do not need to know which page is next in the flow. page1a.jsp

12 What Is Struts? Project from the Apache Software Foundation Open source framework for MVC Web-based applications XML-driven controller servlet De facto standard for JSP Model 2 development Partially declarative, partially coded Often used with other view layers Tiles: A page layout mechanism using JSP templates Velocity: Page scripting language What Is Struts? The core of the Struts framework is a flexible control layer based on standard technologies such as Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta common packages. Struts encourages application architectures based on the JSP Model 2 approach, where application flow is mediated by a central controller. Struts provides its own controller component and integrates with other technologies to provide the model and the view. For the model, Struts can interact with standard data access technologies, such as Java Database Connectivity (JDBC) and Enterprise JavaBeans (EJB), as well as most third-party packages, such as Hibernate, iBATIS, or Object Relational Bridge. For the view, Struts works well with JavaServer Pages (JSPs), including JavaServer Pages Standard Tag Library (JSTL) and JavaServer Faces (JSF), as well as Velocity Templates, Extensible Stylesheet Language Transformation (XSLT), and other presentation systems. A Model 1 implementation of an application relies on page navigation that is embedded into JSPs. This technique was used extensively for Web applications written before the advent of controllers and Model 2 implementation. The difficulty with Model 1 implementations was that navigation grew to be virtually unmanageable. Changes to application flow are very time consuming and error prone. Model 2, using a controller, makes this effort significantly easier.

13 Struts Components View Controller Model Tags JSP Action Form
Resource Bundle Controller Struts Config Controller Servlet Action Struts Components This diagram illustrates the relationships that exist between all components of a Struts-based application. The controller servlet focuses on the flow of the application, and the JSPs focus on the presentation. Each component is reviewed in detail in the following pages. Model Model

14 Struts Components Struts Controller Servlet: Handles requests and marshals results Struts configuration file: The roadmap for the servlet Actions: Processes a request and sends an action forward ActionForms: Passes information between the client and the model TagLibs: Set of Struts library tags usable in JSPs Resource bundles: Text-based file used for internationalization of messages Struts Components (continued) The list above gives a brief introduction about Struts components and their role. JDeveloper provides some additional components that facilitate the development of a Struts-based application. Each of these components is described in detail later in this lesson.

15 Struts Components Flow
HTTP Request Struts Controller Servlet Action Form Action validate() Model Forward Return Response Struts Components Flow This diagram illustrates the generic principle of the flow process in Struts: The ActionServlet (Struts Controller Servlet) class receives and routes the HTTP traffic to the appropriate handler in the framework. If no ActionForm is associated to the action, then it moves on to the action. Otherwise, the validate() method of ActionForm performs a validation check. If validation fails on ActionForm, it returns an error. Otherwise, it moves on to the action. The execute() method of the action sends an ActionForward to the controller. The method may use information from the model. The ActionForward sends a response back to the requester. execute() Page

16 Struts Components: The Controller Servlet
Controls the overall application process Does not appear in the Applications Navigator pane of JDeveloper Is referenced in the web.xml file Is designed to be extended Is driven by XML Controller Servlet The ActionServlet class is part of the org.apache.struts.action package; it extends the HttpServlet class. It needs to be referenced in the web.xml file. Even though you can write your own classes to extend the Struts servlet, Struts provides you with a built-in working solution.

17 Struts Components: The Configuration file
Is named struts-config.xml Is used by the controller servlet Provides the metadata that defines the application: Action mappings (abstractions) Page flow Data flow Exception handling Resources Struts Configuration File The ActionMapping class encapsulates how the Uniform Resource Identifier (URI) request should be mapped to the appropriate Action class. An action mapping can either use a form bean or not. Actions that use a form bean are those that require some type of data input. An action mapping is specified in the struts-config.xml file. Example of an action mapping definition: <action-mappings> <action path="/ValidateLogin" type="mypackage1.ValidateLoginAction" name="ValidateLoginForm" input="/Login.jsp" scope="request"> </action-mappings> The logical name specified in the path attribute must map to a valid Action class or JSP. In the above example, the mapping is specified as an Action class that requires a form bean.

18 Struts Components: Actions
Actions process requests, via its execute() method, and return ActionForward objects that identify where control should be forwarded. Actions are adapters between HTTP requests and the corresponding business logic . The possible tasks that can be specified for an action are: Forward to/represent a page Encode page flow logic Take data from the page and update the model Action Classes The org.apache.struts.action.Action class acts as a bridge between the client request and the business operation. The Action class processes an HTTP request and returns an ActionForward object for the response. An action exists for each logical request. The controller selects an appropriate action for each request based on ActionMapping defined in the struts-config.xml file and then calls the execute() method. The Action class can implement logic in its execute() method. However, logic that accesses a database should be performed by calling an appropriate method of a bean. This is done by refactoring the Action class. The return type of the ActionForward object tells the controller where it should forward. This can be a JSP or another action.

19 Struts Components: ActionForms (Form Beans)
Represent HTML form data that the user enters Shuttle data between the view and the action: Fields in the page are populated from the ActionForm. On submit, the ActionForm is repopulated from the page. Populated ActionForm is passed to the handling action for processing. ActionForm Classes The ActionForm is used by the JSP to transfer the state between the view and the model components. The instance of an ActionForm is created when the action being processed is populated with the appropriate information from the request parameters in the incoming request. An ActionForm can be associated to multiple forms in an application. Generally, a one-to-one relationship between an ActionForm and an input form is used. An ActionForm class has the getter and setter methods of the input fields contained in a form. The corresponding names must be an exact match including case. Even if there is no business logic contained in an ActionForm, the validate() method can perform a first-level validation before the execute() method of the action being called. This validation can return an error message to the related JSP.

20 Struts Components: Tag Libraries
Tag libraries integrate the JSP and controller components <html:form/> – Directs the controller to the correct action on submit <html:errors/> – Displays any errors thrown by the model, including validation <bean:message/> – Outputs a string from the resource file (a field label, for example) Much overlap with “newer” tag libraries, for example JSTL Tag Libraries Struts provides its own set of tag libraries to use in your JSPs. The three tags that you use most are <html:form/>, <html:errors/>, and <bean:message/>. However, the remainder of these tags are also available in other standard tag libraries such as JavaServer Pages Standard Tag Library (JSTL). When possible, it is recommended to use the JSTL tags over the Struts-specific tags.

21 Application Resources File
Centralizes all messages for the application, making message maintenance and internationalization easy to perform Has default name ApplicationResources.properties Associates a key name to a value Is used with the Struts tags and error routines link.logonpage = Click here to Login <html:link page="/logonPage.do"> <bean:message key="link.logonPage"/> </html:link> Application Resources File Your Struts project will define one or more resource bundles (the default resource file created by JDeveloper is named ApplicationResources.properties), which will be used to look up all errors and strings for the struts JSP tags. In the example above, the <bean:message> tag is used in a JSP as a placeholder for the value that corresponds to the key “link.logonPage”. This value is defined in the ApplicationResources.properties file (and thus, is displayed in the JSP at run time) as “Click here to Login.” You can for convenience have multiple files to help organize the project. These just need to be added as separate <message-resources> elements in the file.

22 Internationalizing Your Application
To internationalize an application, perform these steps: Create other bundle files. Add the country code to the file name such as ApplicationResources_fr.properties. Translate the message text: logon.title=Entrez votre nom d’utilisateur The servlet then checks the browser locale variable at startup, and the corresponding file is loaded if found; otherwise the default file is loaded. Internationalizing Your Application For each properties file you can create translated versions (named with the trailing _country code for example, ApplicationResources_fr.properties). The servlet checks the browser locale at startup and loads the correct translation automatically. If a translated version cannot be found, then it falls back to the main version.

23 Struts in Oracle JDeveloper 10g
JDeveloper supports Struts 1.1. You can visualize the page flow from the modeler and: Drill down to JSP/UIX Visual Editor for pages Drill down to Code Editor for actions You can edit in whatever way you choose: Visually Through the Structure pane and Property Inspector In the XML Struts in JDeveloper Having seen the general properties of a Struts application, let us now discover how JDeveloper supports Struts-oriented development. JDeveloper provides a set of tools to assist you in building a Struts application. The Page Flow Diagram is a graphical representation of the struts-config.xml file. It can be used as the central tool to develop an application. Double-clicking any component represented in the diagram accesses the corresponding code.

24 Struts Configuration File
It is written in XML. It is the road map of the application. It can be cumbersome to update directly. JDeveloper provides a graphical editing tool, free of XML syntax. <struts-config> <action-mappings> <action path="/action1"> <forward name="success" path="/page1.do"/> </action> </action-mappings> <message-resources parameter="view.ApplicationResources"/> </struts-config> Struts Configuration File The Struts configuration file (usually named struts-config.xml) is the road map of the application. This is where the logical flow of the application is defined by using XML syntax. This file is the primary source of information that is used by the Struts controller. It specifies all the possible roads or paths (forwards) that the application can go to and describes Form Beans, actions, actionMappings, resource bundles, data sources, and other resources that your application may require. To update this file in JDeveloper, you can edit the XML file either directly or via the Page Flow Diagram. Whichever method you choose, the XML document and the diagram are fully synchronized, so that the changes made in the diagram are reflected in the XML file and vice versa. There are three ways to edit the file: Type XML: Click the Source tab of the struts-config.xml file. Drag and Drop: Click the Page Flow Diagram tab of the struts-config.xml file Use the Structure Pane and Property Inspector: Right-click an element in the Structure pane and edit the properties for a new or existing element by using the Property Inspector.

25 Defining the struts-config.xml File Content
The Structure pane and Property Inspector <struts-config> <action-mappings> <action path="/action1" type="view.Action1Action"> <forward name="success" path="/page1.do"/> </action> <action path="/page1" forward="/page1.jsp"/> </action-mappings> <message-resources parameter="view.ApplicationResources"/> </struts-config> The struts-config.xml File Using the Structure pane and the Property Inspector is one of the ways in which you can interact with the Struts configuration file. Any component that needs to be defined in the struts-config.xml file can be created, edited, and updated by using the Structure pane. These components include data sources, Form Beans, actionMappings, global exceptions, global forwards, controller, message resources, and plug-ins.

26 Defining the struts-config.xml File Content
Using the Struts Configuration Editor <struts-config> <action-mappings> <action path="/action1" type="view.Action1Action"> <forward name="success" path="/page1.do"/> </action> <action path="/page1" forward="/page1.jsp"/> </action-mappings> <message-resources parameter="view.ApplicationResources"/> </struts-config> Using the Struts Configuration Editor An alternative way to define the content of the Struts configuration file is to use the Struts Configuration Editor. To open the editor, right-click the struts-config.xml file in the Applications Navigator, and select Edit Struts-Config.

27 Defining the struts-config.xml File Content
The Struts Page Flow Diagram and Component Palette <struts-config> <action-mappings> <action path="/logon" type="view.LogonAction"> <forward name="success" path="/customers.do"/> </action> <action path="/customers" forward="/customers.jsp"/> <action path="/orders" forward="/orders.jsp"/> </action-mappings> <message-resources parameter="view.ApplicationResources"/> </struts-config> The struts-config.xml File JDeveloper provides a page flow modeling tool that you can use to visualize the action forward mappings of a Struts-based Web application, called the Page Flow Diagram. Use the Page Flow Diagram to design your page flow by using standard Struts elements that you select from the Component Palette. The Page Flow Diagram that you create for your application maintains the Struts configuration file (struts-config.xml) in your project. To open the Struts Page Flow Modeler from your project: If your project does not already contain the WEB-INF folder with the struts-config.xml file, add Struts support to your project. Expand the WEB-INF folder in the Applications Navigator and double-click the struts-config.xml file. The Page Flow Diagram is opened by default by clicking the first tab of the editor, and the XML itself is located in the Source tab.

28 Creating a Page Flow Diagram
Using the Component Palette, drag components to the diagram. Components do not exist until you physically create them (either as a Java class or a JSP). Creating a Page Flow Diagram The components available in the Component Palette for the Page Flow Editor are slightly different from the native Struts components. These components are: Action, Data Action, Page, Data Page, Page Forward, Forward, and Page Link. To draw a component on the Page Flow Diagram, drag the component to the diagram. When creating a new component on the page flow, the component appears with an exclamation mark (!). At that stage, these components are considered “unimplemented.” It is important to note that the unimplemented component does not physically exist until you transform it into a physical one, which can be a Java class file or a page. Double-click an unimplemented component to create the corresponding class or page. After a component is implemented, the icon is updated. Instructor Note At this point, you may want to demonstrate how to create a Struts application and drag an action, forward, and page forward to the Page Flow Diagram.  Show students how the diagram, source code, Structure pane, and Property Inspector stay synchronized and how to edit the application configuration by using these tools.

29 Struts Components: Actions
To create an action: Use the Action icon to draw actions and ActionForms on the Page Flow Diagram Specify the path name for the action The path name is a logical name Modify the execute() method Return a forward Struts Components: Actions An action is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request. The action package is the core of the Struts framework, representing the controller layer of an MVC model. All actions are subclassed from org.apache.struts.action.Action. The HTTP request and response objects are passed to the execute() method of an action. Any processing needed is written in the execute() method, which returns a forward to continue to the next page or action in the flow of the application.

30 Struts Components: Pages and Page Forwards
Pages symbolize the user’s view. Creating a page forward (also called ActionForward): Creates an action entry in the struts-config.xml file Creates a logical name associated with the page name Creating a page Makes a direct reference to the page name Requires to be changed for every occurrence of the page when renaming it Pages need to physically exist to be used as the target of a forward or link Struts Components: Pages and Page Forwards In the Struts Page Flow Diagram, the page forward that you select from the Component Palette represents a Struts action that always forwards to a Web page in your application. Use the dialog box to identify the destination Web page for the page forward in one of these ways: Use the default Web page name, which is the name of the Page Forward icon in the Page Flow Diagram. Locate an existing Web page from your client project. Name a new Web page and open it in the Visual Editor to begin immediately laying out the page. Enter the name of the actual presentation page (.jsp , .uix, or .html) to which you want to declaratively associate an action forward mapping. You can also create page components, which are simply a reference to a JSP, UIX, or HTML page.

31 Struts Components: Forwards and Links
A link represents a flow between components You can create a link (unnamed dotted line): Between pages Between a page and an action You can create a forward (named line): Between actions Between an action and a page Default name of the first forward is Success. More than one forward or link may exist at the source of a component. Struts Components: Forwards and Links Page Link A page link can originate from a page or page forward and have any Struts component as a target. Forward A forward originates from an action and can have any Struts component as a target.

32 ADF Components: DataAction and DataPage
ADF provides two specialized action-subclassed components: DataPage Create for databound pages Used extensively in default ADF business component applications Combination of a DataAction and a standard Struts Page Forward DataAction Create as a standalone action for executing custom methods of the business service Handles standard actions from databound pages ADF Components: DataAction and DataPage One of the difficulties with Struts is the integration of model elements and managing data persistence. JDeveloper provides a solution to this problem. The solution enables you to focus on business logic rather than model integration. The two components are DataActions and DataPages. DataAction and DataPage are specializations of normal Struts components. The DataPage acts as a handler for a databound JSP or UIX page, in that it understands the ADF Model layer and does all the work of handling standard actions. The DataAction is designed for use with custom methods of the business service layer.

33 Summary In this lesson, you should have learned the following about Struts applications: The Struts controller servlet intercepts each request. The struts-config.xml file defines components: Actions (Processes a request) Action Forwards (Pass HTML form data) Page Forwards and/or Pages (Symbolize the user’s view of an action's result) Resource Bundles (Componentization of Labels and Text) Navigation (Forwards and Page Links) Summary In this lesson, you have learned that the Struts framework is based on the MVC architecture. It uses a servlet as the controller part. The controller servlet intercepts each request and passes data among components defined in the struts-config.xml file. The file also defines the navigation for the application, using forward and page link components. JDeveloper provides the Struts framework and the Page Flow Diagram for graphically editing the struts-config.xml file.

34 Practice 9-1: Overview This practice covers the following topics:
Creating a Page Flow Diagram Creating a page forward for each screen Associating each of the JSP screens to a specific page forward action. Adding a DataAction between the logon and customer screens. Linking the DataAction to the logon screen


Download ppt "Controlling an Application with Struts"

Similar presentations


Ads by Google