Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this presentation? Why not share!

Like this? Share it with your network

Share

Struts Introduction Course

on

  • 1,721 views

 

Statistics

Views

Total Views
1,721
Views on SlideShare
1,720
Embed Views
1

Actions

Likes
2
Downloads
139
Comments
0

1 Embed 1

http://www.slideshare.net 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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 wasn’t 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, JSP’s 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.
  • A user sitting at a browser clicks a button, link, or types in a url. A Struts Servlet receives that request. It normally hands over the request to a FormAction class. The FormAction class is responsible for validating any form input. Control is then passed on to an Action class. It’s the responsibility of the Action class to call any Model components, such as classes responsible for updating information in a database. The final step is typically to forward to another JSP, thus a response being sent back to the browser.
  • The default Servlet controller is org.apache.struts.action.ActionServlet. This Servlet can be extended by your application, but typically there is no need to. Note that this ONE Servlet controls all of your Struts application. Your application will consist of any number of Java Server Pages. These pages could be list pages, form pages, or any other type of web page. Your application will normally consist of other classes that make up the Model components. These classes can be either standard Java classes of EJB’s, or a combination of both.
  • In using WSAD and Struts, you’ll notice that once you start your application, the web.xml file is read, loads the ActionServlet, which then reads the struts-config.xml file, which has references to all of your form beans (ActionForms), Action beans, and the navigation your application will use.
  • Many requirements documents used for building web applications focus on the View . However, you should ensure that the processing required for each submitted request is also clearly defined from the Model's perspective. In general, the developer of the Model components will be focusing on the creation of JavaBeans classes that support all of the functional requirements. The precise nature of the beans required by a particular application will vary widely depending on those requirements, but they can generally be classified into several categories.
  • EJB’s are the industry standard for Java Model components. With that said, you’ll find that you don’t always use them. There is nothing to prevent you from connecting to a database, performing a SQL statement, and then returning the result set from any type of Java class. In grammatical terms, we might think about state information as nouns (things) and actions as verbs (changes to the state of those things).
  • 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.
  • Although business logic should not be directly included in the ActionForm class, it is a good idea to call Java Beans or Enterprise Java Beans that contain the business logic from your ActionForm. If an error is then identified by calling the business logic, an ActionError can easily be generated.
  • When defining your getter and setter methods, make sure the names match with what were specified within the form on the Java Server Page. For example, if you defined a text field within your form named firstName, you should define a private String property with a getFirstName() and setFirstName() methods.
  • For small scale systems, or for state information that need not be kept for a long period of time, a set of system state beans may contain all the knowledge that the system ever has of these particular details. Or, as is often the case, the system state beans will represent information that is stored permanently in some external database (such as a CustomerBean object that corresponds to a particular row in the CUSTOMERS table), and are created or removed from the server's memory as needed. Entity Enterprise JavaBeans are also used for this purpose in large scale applications.
  • 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.
  • One of the reasons to place business logic into an EJB is for scalability. If a particular business logic bean was referenced in numerous applications as a regular Java Bean, this would take additional resources. If that business logic is written within an EJB, it would only be instantiated once.
  • Although Struts provides a mechanism within the struts-config.xml file to define data sources, WebSphere provides a similar mechanism which also includes a more sophisticated connection pool.
  • This unit focuses on the task of building the View components of the application, which will primarily be created using Java Server Pages (JSP) technology. In particular, Struts provides support for building internationalized applications, as well as for interacting with input forms.
  • With the use of a property files, Struts has the capability to handle multiple languages. Instead of placing text directly within your Java Server Pages, a Struts bean tag is used to get that information from a property file. If for example you need to also support Spanish, a second property file would be defined with the same name as the original with an “_es” appended to the name. This property file would have the Spanish text. The browser recognizes what language the user has set for their default, and Struts uses that to know which property file to reference.
  • When you configure the controller Servlet in the web application deployment descriptor, one of the things you will need to define in an initialization parameter is the base name of the resource bundle for the application. action org.apache.struts.action.ActionServlet application MyResources
  • At one time or another, most web developers have built forms using the standard capabilities of HTML, such as the tag. Users have come to expect interactive applications to have certain behaviors, and one of these expectations relates to error handling -- if the user makes an error, the application should allow them to fix just what needs to be changed -- without having to re-enter any of the rest of the information on the current page or form. Fulfilling this expectation is tedious and cumbersome when coding with standard HTML and JSP pages. For example, an input element for a username field might look like this (in JSP): "/> which is difficult to type correctly, confuses HTML developers who are not knowledgeable about programming concepts, and can cause problems with HTML editors. Instead, Struts provides a comprehensive facility for building forms, based on the Custom Tag Library facility of JSP 1.1. The case above would be rendered like this using Struts: with no need to explicitly refer to the JavaBean from which the initial value is retrieved. That is handled automatically by the framework. HTML forms are sometimes used to upload other files. Most browsers support this through a element, that generates a file browse button, but it's up to the developer to handle the incoming files. Struts handles these "multipart" forms in a way identical to building normal forms.
  • Notice line 2 and 3. These reference the Struts tag libraries. A tag library ends with a “.tld” extension. Struts has several tag libraries that you’ll end up using. This section of a JSP is only referencing the Struts html and bean tag libraries. Notice the prefix, and then how that prefix is used to reference a text field for example.
  • The tag libraries should first be referenced within the web.xml file. The taglib directive within the Java Server Page typically references the uri specified within the web.xml file. There are two ways to use the error tags. You can have one place within your Java Server Page to show all errors, or you can place an error tag close to each field that may result in an error condition. These error conditions are created within your ActionForm class.
  • Within the section in the struts-config.xml file, you would define a form tag like the following: < form-bean name = "CustomerFormBean" type = "com.pri.javaTraining.CustomerForm" /> This tag is also referenced within the tag in the struts-config.xml file, like the following: < action path = "/CustomerAction" type = "com.pri.javaTraining.CustomerAction" name = "CustomerFormBean" scope = "request" input = "/pgcustomer.jsp" > < forward name = "Save" path = "/pgindex.jsp" /> < forward name = "Add Account" path = "/pgaddaccount.jsp" /> < forward name = "Cancel" path = "/pgindex.jsp" /> </ action >
  • In every case, a field tag must be nested within a form tag, so that the field knows what bean to use for initializing displayed values. The form "field" tags in the Struts-HTML tag library share a common set of tag attributes that have the same meaning, no matter what field tag they are used with. These properties also accept Runtime Expressions, meaning you can set them with a scriptlet.
  • Below is an example of using both the and tags. The tag in this example checks for a value from the SessionBean object by calling the getCurrentCustomerAccounts() method. This is done automatically by placing a reference of “CustSessionBean” which points to the tag, which references the SessionBean class within the session block. The property attribute is then used to look for the method with a “get” and the same name as what is specified within the property attribute, with the first character being uppercase. The example below also demonstrates the use of the tag. This is one of the most useful tags within Struts. This tag is also using the SessionBean object mentioned above. It also is calling the same getCurrentCustomerAccounts() method. This method returns a class that is within the Collection family of classes. In this particular example, it is using a Vector. The Vector was loaded with a class named CheckingAccount. The CheckingAccount class has the following methods: getAccountNo(), getAccountTypeString(), getStatusCode(), getBalance(), and getOpenDateFormatted(). Notice on the tag the id attribute is named “aAccount”. This is then referenced within the tag by specifying a name attribute with the same value. The property attribute within the tag is used to call the appropriate method on whatever class that is within the Vector (or other Collection type class). < jsp:useBean id = "CustSessionBean" scope = "session" class = "com.pri.javaTraining.SessionBean" /> < logic:present name = "CustSessionBean" property = "currentCustomerAccounts" > < logic:iterate id = "aAccount" name = "CustSessionBean" property = "currentCustomerAccounts" > < TR > < TD >< bean:write name = "aAccount" property = "accountNo" /></ TD > < TD >< bean:write name = "aAccount" property = "accountTypeString" /></ TD > < TD >< bean:write name = "aAccount" property = "statusCode" /></ TD > < TD >< bean:write name = "aAccount" property = "balance" /></ TD > < TD >< bean:write name = "aAccount" property = "openDateFormatted" /> </ TR > </ logic:iterate > </ logic:present >
  • It is a good idea to use the Struts tags instead of the plain HTML tags. Some of these tags may not provide much additional capabilities, but they can be extended. If extended, you can provide whatever additional capabilities you need.
  • The validate() method has the following options: Perform the appropriate validations and find no problems -- Return either null or a zero-length ActionErrors instance, and the controller servlet will proceed to call the perform() method of the appropriate Action class. Perform the appropriate validations and find problems -- Return an ActionErrors instance containing ActionError 's, which are classes that contain the error message keys (into the application's MessageResources bundle) that should be displayed. The controller servlet will store this array as a request attribute suitable for use by the tag, and will forward control back to the input form (identified by the input property for this ActionMapping ). As mentioned earlier, this feature is entirely optional. The default implementation of the validate() method returns null , and the controller servlet will assume that any required validation is done by the action class. One common approach is to perform simple, prima facia validations using the ActionForm validate() method, and then handle the "business logic" validation from the Action.
  • Another approach to this would be to use the Struts Template Tag library.
  • When creating a browser based application, it is typical to have some type of common navigation on each Java Server Page. One of the easiest approaches to providing this is by placing the common navigation into a file that is later included in the specific Java Server Page.
  • The Controller portion of the application is focused on receiving requests from the client (typically a user running a web browser), deciding what business logic function is to be performed, and then delegating responsibility for producing the next phase of the user interface to an appropriate View component. In Struts, the primary component of the Controller is a servlet of class ActionServlet . This servlet is configured by defining a set of ActionMappings . An ActionMapping defines a path that is matched against the request URI of the incoming request, and usually specifies the fully qualified class name of an Action class. All Actions are subclassed from org.apache.struts.action.Action . Actions encapsulate the business logic, interpret the outcome, and ultimately dispatch control to the appropriate View component to create the response.
  • org.apache.struts.action.ActionServlet is the default Servlet that is provided with Struts. This Servlet can be used, or it can be extended. If extended, the extended version should be defined in the web.xml file. For smaller applications, ActionServlet typically provides the necessary functionality. For larger applications, it is typically extended.
  • It is not always necessary to create an Action class for each form within your project. For smaller applications one Action class could provide the necessary functionality for the entire project. However, it is a good practice to create a new Action class for each form. So for a Java Server Page that has a form, an extension of the ActionForm class would be created, and an extension of the Action class would also be created. This allows for easier maintenance. It is also a widely adopted approach within the Struts development community to place a form on EVERY Java Server Page. Even list pages would have a form defined on them. This gives the maximum flexibility to the developer. This approach allows for more flexibility on navigation.
  • The second method is the one used by WebSphere.
  • If is NOT a good practice to “hard code” the name of the Java Server Page that you are forwarding to. Within Struts all Java Server Pages should be specified within the struts-config.xml file. For a particular Action class, multiple forward tags may be specified. Here’s an example: < action path = "/CustomerAction" type = "com.pri.javaTraining.CustomerAction" name = "CustomerFormBean" scope = "request" input = "/pgcustomer.jsp" > < forward name = "Save" path = "/pgindex.jsp" /> < forward name = "Add Account" path = "/pgaddaccount.jsp" /> < forward name = "Cancel" path = "/pgindex.jsp" />
  • Below is a very simple example of an Action class’ perform method: public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { /** Get a handle to the StrutsInputForm */ StrutsInputForm strutsForm = (StrutsInputForm) form; /** Get the action from the form */ String action = strutsForm.getAction(); /** Forward control to the specified success URI */ return (mapping.findForward(action)); }
  • Only define variables within the perform() method, or within methods that you’ve added to the Action class.
  • A common approach to logging is to use another of the Jakarta open source modules named Log4j: http://jakarta.apache.org/log4j/docs/index.html
  • Below is an example of an ActionMapping implementation: < action path = "/CustomerAction" type = "com.pri.javaTraining.CustomerAction" name = "CustomerFormBean" scope = "request" input = "/pgcustomer.jsp" > < forward name = "Save" path = "/pgindex.jsp" /> < forward name = "Add Account" path = "/pgaddaccount.jsp" /> < forward name = "Cancel" path = "/pgindex.jsp" />
  • The two important elements are: This section contains your form bean definitions. You use a element for each form bean, which has the following important attributes: name : A unique identifier for this bean, which will be used to reference it in corresponding action mappings. Usually, this is also the name of the request or session attribute under which this form bean will be stored. type : The fully-qualified Java classname of your form bean. This section contains your action definitions. You use an element for each of your actions you would like to define. Each action element requires the following attributes to be defined: path : The application context-relative path to the action type : The fully qualified java classname of your Action class name : The name of your element to use with this action
  • Below is an example of a typical section: < form-beans > <!-- Struts Example form bean --> < form-bean name = "StrutsInputFormBean" type = "org.struts.example.StrutsInputForm" /> < form-bean name = "StrutsDisplayFormBean" type = "org.struts.example.StrutsDisplayForm" /> </ form-beans >
  • Below is an example of a typical < action-mappings > section: < action-mappings > <!-- StrutsExample --> < action path = "/StrutsInputPath" type = "org.struts.example.StrutsInputAction" name = "StrutsInputFormBean" scope = "request" input = "/PgInput.jsp" > < forward name = "Next" path = "/PgDisplay.jsp" /> </ action > < action path = "/StrutsDisplayPath" type = "org.struts.example.StrutsDisplayAction" name = "StrutsDisplayFormBean" scope = "request" input = "/PgDisplay.jsp" > </ action > </ action-mappings >
  • This is a section that will probably NOT be used when running an application server such as WebSphere. WebSphere has a much more sophisticated connection pooling mechanism.
  • We’re going to go over both the struts-config.xml and the web.xml files in later chapters.
  • You can find links to each tag library at the following URL under the Developer’s Guide: http://jakarta.apache.org/struts/doc-1.0.2/index.html. When developing Java Server Pages, a developer has the capability to imbed Java code. However, this is considered a bad approach. Through the use of the Struts tag libraries, and custom tag libraries, a developer should be able to create Java Server Pages without ANY Java code imbedded. Actually a widely accepted practice is to have a Business Analyst with web page design experience to create the Java Server Page. Once they have the “look and feel” completed, they would turn that Java Server Page over to the developer, who would add whatever additional capabilities that were necessary.
  • 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 tag The 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.
  • Each of these would typically be prefixed with <html:. The Struts web site goes into detail about each tag: http://jakarta.apache.org/struts/api/org/apache/struts/taglib/html/package-summary.html#package_description
  • 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 you’re NOT constrained with those limitations.
  • Notice the <input type=“text” html tag. One major difference is the property attribute, and this is important. The name you specify in the property tag, is what Struts uses to know which getter and setter methods to call. For example, if the property name is “state”, the getter method would be getState(), and the setter method would be setState. If a property name was “firstName”, the getter method would be getFirstName(), and the setter method would be setFirstName().
  • Much of the power of JavaServer Pages (JSP) technology comes from the simple and powerful mechanisms by which the servlet that is generated automatically from your JSP source page can interact with JavaBeans that represent the computational state of your application. In standard JSP pages, the tag is used create a bean (if necessary), as well as a "scripting variable" that can be used within scriptlets to refer to these beans.
  • Two of the above tags that you’ll use frequently are the “message” and “write” tags. You use the “message” tag to retrieve text messages from the application resources file (whatever.properties). The “write” tag is used to display information that has either been entered or been retrieved from a database.
  • This JSP shows the use of the bean message and bean write tags. On the bean message tag, you specify a key name. This key name references an entry into your application resources file. On the bean write tag, you specify a name attribute which references the id of the iterate tag. You also specify a property name which references a getter method on the form bean that’s referenced by the “ImageLocationListForm”.
  • One question that may come up at this point is why not just put Java code into your JSP? The answer to that question is answered by referring back to the roles we’ve defined for doing this kind of development. The idea is to have someone that is not a programmer be able to create and maintain the JSP’s. This allows someone that has creative skills to create attractive and easy to use web pages. This also frees up the developer from what they normally consider tedious and time consuming tasks.
  • For further information on the Logic Tags, visit: http://jakarta.apache.org/struts/api/org/apache/struts/taglib/logic/package-summary.html#package_description
  • Many of the tags in this tag library will throw a JspException at runtime when they are utilized incorrectly (such as when you specify an invalid combination of tag attributes). JSP allows you to declare an "error page" in the directive. If you wish to process the actual exception that caused the problem, it is passed to the error page as a request attribute under key org.apache.struts.action.EXCEPTION .
  • For further information on the Logic Tags, visit: http://jakarta.apache.org/struts/api/org/apache/struts/taglib/logic/package-summary.html#package_description
  • Notice the tag. The next line shows a <logic:equal tag. If the value does equal “Insert”, a title of “Insert” is displayed. By using this approach we were able to use the same JSP for both a page to perform updates to existing data, and the capability to insert new records.
  • The Template library supplies tags that are useful for creating dynamic JSP templates for pages which share a common format.
  • For further information on Template Tags, visit: http://jakarta.apache.org/struts/api/org/apache/struts/taglib/template/package-summary.html#package_description
  • This JSP shows the use of custom tags. Note the tag. This tag has other customer tags nested within it. The purpose of this link tag is to take the values of the attributes passed to it, along with the values of the other custom tags nested within it, and create an XML document that can be passed to another web server. It actually encrypts the XML document, and embeds that data within a form with a submit button. The user is then able to click the button or link and they’re directed to one of the image servers, and an image is displayed. Below is the html source from what gets generated from the custom tags above: <a>EOBs/REMITS (via Doc Handle)</a>
  • This displays what is needed in creating a “tld” file. You define what the name of the tag is, what Java class is responsible for processing the tag, and whatever attributes are needed to support the tag.
  • This displays a Tag class. A typical tag class has a doStartTag() and a doEndTag() method. You decide which of these you need to override. Sometimes it will be both.
  • How does the controller Servlet learn about the mappings you want? Struts includes a Digester module that is capable of reading an XML-based description of the desired mappings, creating the appropriate objects along the way.
  • The two important elements are: This section contains your form bean definitions. You use a element for each form bean, which has the following important attributes: name : A unique identifier for this bean, which will be used to reference it in corresponding action mappings. Usually, this is also the name of the request or session attribute under which this form bean will be stored. type : The fully-qualified Java classname of your form bean. This section contains your action definitions. You use an element for each of your actions you would like to define. Each action element requires the following attributes to be defined: path : The application context-relative path to the action type : The fully qualified java classname of your Action class name : The name of your element to use with this action
  • Notice the tag section. Within this section you use the tag section. Within this section you use the tag section. Within this section you use the &lt;action tag and assign several values. The first attribute is path, and is referenced by acion=“” within a JSP form. The next attribute (type), describes the name of the Action class. This class referenced here is always a decendent of org.apache.
  • The web.xml file is not something only used for Struts. It’s used in all J2EE web applications. It does have references to things that are Struts specific though.
  • Note that a web.xml file is not unique to Struts. When using WSAD and generating a web project, a web.xml file is automatically generated. However, it does not contain much that is useful. Typically a developer copies a web.xml file from an existing Struts based project, and then modifies it.
  • Note the line that has the tag. It references the org.apache.struts.action.ActionServlet class. If you extend this class due to the necessity to provide additional functionality, you will need to reference your extended class here. Also not the tag with the value of application. The following tag is where you reference your projects property file.
  • Note the tag. The value specified here is the start page of your application. This can either be an html file, or a Java Server Page. There are two common approaches to defining the URLs that will be processed by the controller Servlet -- prefix matching and extension matching. An appropriate mapping entry for each approach is described below. Prefix matching means that you want all URLs that start (after the context path part) with a particular value to be passed to this Servlet. Such an entry might look like this: action /execute/* which means that a request URI to match the /logon path described earlier might look like this: http://www.mycompany.com/myapplication/execute/logon where /myapplication is the context path under which your application is deployed. Extension mapping, on the other hand, matches request URIs to the action servlet based on the fact that the URI ends with a period followed by a defined set of characters. For example, the JSP processing servlet is mapped to the *.jsp pattern so that it is called to process every JSP page that is requested. To use the *.do extension (which implies &quot;do something&quot;), the mapping entry would look like this: action *.do and a request URI to match the /logon path described earlier might look like this: http://www.mycompany.com/myapplication/logon.do
  • An entry defining the Struts tag library must be included in the web.xml file. If any custom tag libraries are used they must also be defined here.
  • Application Resource or property files are not unique to Struts applications. However, with the internationalization support built into Struts, they are used more.
  • Above is an example of an application resources property file. This file can contain any number of items. The one above shows examples of error messages, and text values used for things such as a title in your Java Server Page or the text on a button.
  • Many resources are available on the Internet. Currently there is only one published book on Struts, and it is not recommended by the author of these slides.
  • They’re many sites with Struts information. The third bullet item above displays a link to a page on the main Struts site which has links to many other sites. One other item worth mentioning is that IBM uses Struts. Some of the example projects included with WSAD use Struts.

Struts Introduction Course Presentation Transcript

  • 1. STRUTS Part of the Jakarta Project Sponsored by the Apache Software Foundation Developed by: Roger W Barnes of Project Refinery, Inc. Introduction to Struts
  • 2. STRUTS Objectives
    • Course Overview
    • Unit 1 - Model-View-Controller Design Pattern
    • Unit 2 - Model Components
    • Unit 3 - View Components
    • Unit 4 - Controller Components
    • Unit 5 - Tag Libraries
  • 3. STRUTS Objectives
    • Unit 6 - STRUTS Configuration File
    • Unit 7 - Web Application Descriptor File
    • Unit 8 - Application Resources File
    • Unit 9 – Resources
  • 4. Model-View-Controller Design Pattern Unit 1
  • 5. STRUTS MVC Design Pattern
    • 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
  • 6. STRUTS MVC Design Pattern
  • 7. STRUTS MVC Design Pattern
    • 3 Major Components in STRUTS
      • Servlet controller (Controller)
      • Java Server Pages (View)
      • Application Business Logic (Model)
    • Controller bundles and routes HTTP request to other objects in framework
    • Controller parses configuration file
  • 8. STRUTS MVC Design Pattern
    • 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
  • 9. Model Components Unit 2
  • 10. STRUTS Model Components
    • Model divided into concepts
      • Internal state of the system
      • Actions that can change that state
    • Internal state of system represented by
      • JavaBeans
      • Enterprise JavaBeans
  • 11. STRUTS Model Components
    • JavaBeans and Scope
      • Page – visible within a single JSP page, for the lifetime of the current request
      • Request – visible within a single JSP page, as well as to any page or servlet that is included in this page, or forwarded to by this page
      • Session – visible to all JSP pages and servlets that participate in a particular user session, across one or more requests
      • Application - visible to all JSP pages and servlets that are part of a web application
  • 12. STRUTS Model Components
    • ActionForm Beans
      • Extends the ActionForm class
      • Create one for each input form in the application
      • If defined in the ActionMapping 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 automatically
        • 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 these values immediately available
  • 13. STRUTS Model Components
    • When coding ActionForm beans consider:
      • The ActionForm class itself requires no specific methods to be implemented. It is used to identify the role these particular beans play in the overall architecture. Typically, an ActionForm bean will have only property getter and property setter methods, with no business logic
      • The ActionForm object also offers a standard validation mechanism. If you override a &quot;stub&quot; method, and provide error messages in the standard application resource, Struts will automatically validate the input from the form
  • 14. STRUTS Model Components
    • Continued
      • Define a property (with associated getXxx() and setXxx() methods) for each field that is present in the form. The field name and property name must match according to the usual JavaBeans conventions
      • Place a bean instance on your form, and use nested property references. For example, you have a &quot;customer&quot; bean on your Action Form, and then refer to the property &quot;customer.name&quot; in your JSP view. This would correspond to the methods customer.getName() and customer.setName(string Name) on your customer bean
  • 15. STRUTS Model Components
    • System State Beans
      • Actual state of a system is normally represented as a set of one or more JavaBeans classes, whose properties define the current state
      • A shopping cart system, for example, will include a bean that represents the cart being maintained for each individual shopper, and will (among other things) include the set of items that the shopper has currently selected for purchase
  • 16. STRUTS Model Components
    • Business Logic Beans
      • Should encapsulate the functional logic of your application as method calls on JavaBeans designed for this purpose
      • For maximum code re-use, business logic beans should be designed and 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
  • 17. STRUTS Model Components
    • Business Logic Beans - Continued
      • For larger applications, these beans will often be stateful or stateless Enterprise JavaBeans (EJBs)
  • 18. STRUTS Model Components
    • Accessing Relational Databases
      • Struts can define the datasources for an application from within its standard configuration file
      • A simple JDBC connection pool is also provided
  • 19. View Components Unit 3
  • 20. STRUTS View Components
    • Internationalized Messages
      • Struts builds upon Java platform to provide assistance for building internationalized and localized applications
        • Locale - fundamental Java class that supports internationalization
        • ResourceBundle - supports messages in multiple languages
        • PropertyResourceBundle - standard implementation of ResourceBundle that allows you to define resources using the same &quot;name=value&quot; syntax used to initialize properties files
        • MessageFormat - allows you to replace portions of a message string with arguments specified at run time
        • MessageResources - lets you treat a set of resource bundles like a database, and allows you to request a particular message string for a particular Locale
  • 21. STRUTS View Components
    • ApplicationResources.properties
      • Contains the messages in the default language for your server. If your default language is English, you might have an entry like this: prompt.hello=Hello
    • ApplicationResources_xx.properties
      • Contains the same messages in the language whose ISO language code is &quot;xx&quot;
  • 22. STRUTS View Components
    • Forms and FormBean interactions
      • HTML Forms and their limitations
      • Errors not easily handled
  • 23. STRUTS View Components
    • <%@ page language=&quot;java&quot; %>
    • <%@ taglib uri=&quot;/WEB-INF/struts-html.tld&quot; prefix=&quot;html&quot; %>
    • <%@ taglib uri=&quot;/WEB-INF/struts-bean.tld&quot; prefix=&quot;bean&quot; %>
    • <html:html>
    • <head> <title> <bean:message key=&quot;logon.title&quot;/> </title>
    • <body bgcolor=&quot;white&quot;>
    • <html:errors/>
    • <html:form action=“/logonpath.do&quot;>
    • <table border=&quot;0&quot; width=&quot;100%&quot;>
    • <tr> <th align=&quot;right&quot;> <html:message key=&quot;prompt.username&quot;/> </th>
    • <td align=&quot;left&quot;> <html:text property=&quot;username&quot; size=&quot;16&quot;/> </td> </tr>
    • <tr> <td align=&quot;right&quot;> <html:submit> <bean:message key=&quot;button.submit&quot;/> </html:submit> </td>
  • 24. STRUTS View Components
    • Building Forms with Struts
      • The taglib directive tells the JSP page compiler where to find the tag library descriptor for the Struts tag library
      • message tag is used to look up internationalized message strings from a MessageResources object containing all the resources for this application
      • The errors tag displays any error messages that have been stored by a business logic component, or nothing if no errors have been stored
  • 25. STRUTS View Components
    • Building Forms with Struts – continued
      • The form tag renders an HTML <form> element, based on the specified attributes
      • The form tag also associates all of the fields within this form with a request scoped FormBean that is stored under the key FormName
      • The form bean can also be specified in the Struts configuration file, in which case the Name and Type can be omitted here
      • The text tag renders an HTML <input> element of type &quot;text“
      • The submit and reset tags generate the corresponding buttons at the bottom of the form
  • 26. STRUTS View Components
    • Input field types supported
      • checkboxes
      • hidden fields
      • password input fields
      • radio buttons
      • reset buttons
      • select lists
      • options
      • submit buttons
      • text input fields
      • textareas
  • 27. 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
  • 28. STRUTS View Components
    • Useful Presentation Tags – continued
      • [html] link generates a HTML <a> element as an anchor definition or a hyperlink to the specified URL, and automatically applies URL encoding to maintain session state in the absence of cookie support
      • [html] img generates a HTML <img> element with the ability to dynamically modify the URLs specified by the &quot;src&quot; and &quot;lowsrc&quot; attributes in the same manner that <html:link> can
      • [bean] parameter retrieves the value of the specified request parameter, and defines the result as a page scope attribute of type String or String
  • 29. STRUTS View Components
    • Automatic Form Validation
      • Struts offers an additional facility to validate the input fields it has received
      • To utilize this feature, override the validate() method in your ActionForm class
      • The 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
  • 30. STRUTS View Components
    • Page Composition with Includes
      • The development of the various segments of a site is easier if you can divide up the work, and assign different developers to the different segments
      • Use the include capability of JavaServer Pages technology to combine the results into a single result page, or use the include tag provided with Struts
  • 31. STRUTS View Components
    • Page Composition with Includes – continued
      • There are three types of include available, depending on when you want the combination of output to occur:
        • An <%@ include file=&quot;xxxxx&quot; %> directive can include a file that contains java code or jsp tags
        • The include action ( <jsp:include page=&quot;xxxxx&quot; flush=&quot;true&quot; /> ) is processed at request time, and is handled transparently by the server
        • The bean:include tag takes either a an argument &quot;forward&quot; representing a logical name mapped to the jsp to include, or the &quot;id&quot; argument, which represents a page context String variable to print out to the jsp page
  • 32. Controller Components Unit 4
  • 33. STRUTS Controller Components
    • Struts includes a Servlet that implements the primary function of mapping a request URI to an Action class (ActionServlet)
  • 34. STRUTS Controller Components
    • Your primary responsibilities are:
      • Write an Action class (that is, an extension of the Action class) for each logical request that may be received
      • Write the action mapping configuration file (in XML) that is used to configure the controller servlet (struts-config.xml)
      • Update the web application deployment descriptor file (in XML) for your application to include the necessary Struts components
      • Add the appropriate Struts components to your application
  • 35. STRUTS Controller Components
    • Action Classes:
      • The Action class defines a perform method that you override
        • public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
  • 36. STRUTS Controller Components
    • The goal of an Action class is to process this request, and then to return an ActionForward object that identifies the JSP page (if any) to which control should be forwarded to generate the corresponding response
  • 37. STRUTS Controller Components
    • A typical Action class will implement the following logic in its perform() method
      • Validate the current state of the user's session
      • If validation has not yet occurred, validate the form bean properties as necessary
      • Perform the processing required to deal with this request
      • Update the server-side objects that will be used to create the next page of the user interface
      • Return an appropriate ActionForward object that identifies the JSP page to be used to generate this response, based on the newly updated beans
  • 38. STRUTS Controller Components
    • Design issues to remember when coding Action classes include the following
      • The controller Servlet creates only one instance of your Action class, and uses it for all requests. Thus, you need to code your Action class so that it operates correctly in a multi-threaded environment, just as you must code a Servlet's service() method safely
      • The most important principle that aids in thread-safe coding is to use only local variables, not instance variables, in your Action class
  • 39. STRUTS Controller Components
    • Design issues to remember when coding Action classes include the following – continued
      • The beans that represent the Model of your system may throw exceptions due to problems accessing databases or other resources. You should trap all such exceptions in the logic of your perform() method, and log them to the application logfile
      • As a general rule, allocating scarce resources and keeping them across requests from the same user (in the user's session) can cause scalability problems
  • 40. STRUTS Controller Components
    • The ActionMapping Implementation
        • type - Fully qualified Java class name of the Action implementation class used by this mapping.
        • name - The name of the form bean defined in the config file that this action will use
        • path - The request URI path that is matched to select this mapping. See below for examples of how matching works.
        • unknown - Set to true if this action should be configured as the default for this application, to handle all requests not handled by another action. Only one action can be defined as a default within a single application.
        • validate - Set to true if the validate() method of the action associated with this mapping should be called.
  • 41. STRUTS Controller Components
    • The Actions Mapping Configuration File
      • The developer's responsibility is to create an XML file named struts-config.xml , and place it in the WEB-INF directory of your application
      • The outermost XML element must be <struts-config>
      • Inside of the <struts-config> element, there two important elements that you use to describe your actions:
  • 42. STRUTS Controller Components
        • <form-beans> This section contains your form bean definitions. You use a <form-bean> element for each form bean, which has the following important attributes:
          • name : The name of the request or session level attribute that this form bean will be stored as
          • type : The fully-qualified Java classname of your form bean
  • 43. STRUTS Controller Components
      • <action-mappings> This section contains your action definitions. You use an <action> element for each of your actions you would like to define. Each action element has requires the following attributes to be defined:
        • path : The application context-relative path to the action
        • type : The fully qualified java classname of your Action class
        • name : The name of your <form-bean> element to use with this action
  • 44. STRUTS Controller Components
      • One more section of good use is the <data-sources> section, which specifies data sources that your application can use.This is how you would specify a basic data source for your application inside of struts-config.xml:
        • <struts-config>
        • <data-sources>
        • <data-source autoCommit=&quot;false&quot;
        • description=&quot;Example Data Source Description&quot; driverClass=&quot;org.postgresql.Driver&quot; maxCount=&quot;4&quot; minCount=&quot;2&quot; password=&quot;mypassword&quot; url=&quot;jdbc:postgresql://localhost/mydatabase&quot; user=&quot;myusername&quot;/>
        • </data-sources>
        • </struts-config>
  • 45. STRUTS Controller Components
    • The Web Application Deployment Descriptor
      • The final step in setting up the application is to configure the application deployment descriptor (stored in file WEB-INF/web.xml ) to include all the Struts components that are required
  • 46. Tag Libraries Unit 5
  • 47. STRUTS Tag Libraries
    • HTML Tags
    • Bean Tags
    • Logic Tags
    • Template Tags
    • Custom Tags
  • 48. HTML Tags
    • The tags in the Struts HTML library form a bridge between a JSP view and the other components of a Web application. Since a dynamic Web application often depends on gathering data from a user, input forms play an important role in the Struts framework. Consequently, the majority of the HTML tags involve HTML forms. Other important issues addressed by the Struts-HTML tags are messages, error messages, hyperlinking and internationalization.
  • 49. HTML Tags
    • HTML &quot;form&quot; tags
      • button
      • cancel
      • checkboxes
      • file
      • hidden
      • image
      • multibox
      • password input fields
      • radio buttons
      • reset buttons
    • HTML &quot;form&quot; tags
      • select lists with embedded
      • option
      • options
      • submit buttons
      • text input fields
      • textareas
  • 50. HTML Tags – Typical HTML Form <HTML> <BODY> <FORM> <TABLE WIDTH=&quot;100%&quot;> <TR><TD>First Name</TD> <TD><INPUT TYPE=&quot;TEXT&quot; NAME=&quot;Name&quot; SIZE=&quot;40&quot; MAXLENGTH=&quot;40&quot;></TD></TR> <TR><TD>Street Address</TD> <TD><INPUT TYPE=&quot;TEXT&quot; NAME=&quot;Address&quot; SIZE=&quot;40&quot; MAXLENGTH=&quot;40&quot;></TD></TR> <TR><TD>City</TD> <TD><INPUT TYPE=&quot;TEXT&quot; NAME=&quot;City&quot; SIZE=&quot;20&quot; MAXLENGTH=&quot;20&quot;></TD></TR> <TR><TD>State</TD> <TD><INPUT TYPE=&quot;TEXT&quot; NAME=&quot;State&quot; SIZE=&quot;2&quot; MAXLENGTH=&quot;2&quot;></TD></TR> <TR><TD>Postal Code</TD> <TD><INPUT TYPE=&quot;TEXT&quot; NAME=&quot;ZipCode&quot; SIZE=&quot;9&quot; MAXLENGTH=&quot;9&quot;></TD></TR> <TR><TD ALIGN=CENTER><INPUT TYPE=&quot;SUBMIT&quot; NAME=&quot;Submit&quot; VALUE=&quot;Save&quot;></TD> <TD><INPUT TYPE=&quot;RESET&quot; NAME=&quot;Reset&quot; VALUE=&quot;Cancel&quot;></TD></TR> </TABLE> </FORM> </BODY> </HTML>
  • 51. HTML Tags – Typical Struts Form <HTML:HTML> <BODY> <HTML:FORM Action=&quot;/CustomerForm&quot; focus=“name” > <TABLE WIDTH=&quot;100%&quot;> <TR><TD><bean:message key=&quot;customer.name&quot;/></TD> <TD><HTML:TEXT property=&quot;name&quot; size=&quot;40&quot; maxlength=&quot;40&quot; /></TD></TR> <TR><TD><bean:message key=&quot;customer.address&quot;/></TD> <TD><HTML:TEXT property=&quot;address&quot; size =&quot;40&quot; maxlength =&quot;40&quot; /></TD></TR> <TR><TD><bean:message key=&quot;customer.city&quot;/></TD> <TD><HTML:TEXT property=&quot;city&quot; size =&quot;20&quot; maxlength =&quot;20&quot; /></TD></TR> <TR><TD><bean:message key=&quot;customer.state&quot;/></TD> <TD><HTML:TEXT property=&quot;state&quot; size =&quot;2&quot; maxlength =&quot;2&quot; /></TD></TR> <TR><TD><bean:message key=&quot;customer.zip&quot;/></TD> <TD><HTML:TEXT property=&quot;zip&quot; size =&quot;9&quot; maxlength =&quot;9&quot; /></TD></TR> <TR><TD ALIGN=CENTER><html:submit property=&quot;action&quot; value =&quot;Save&quot;/></TD> <TD><html:reset property=&quot;action&quot; value =&quot;Reset&quot;/></TD></TR> </TABLE> </HTML:FORM> </BODY> </HTML:HTML>
  • 52. Bean Tags
    • The &quot;struts-bean&quot; tag library provides substantial enhancements to the basic capability provided by <jsp:useBean> , as discussed in the following sections:
      • Bean Properties - Extended syntax to refer to JavaBean properties with simple names (same as the standard JSP tags <jsp:getProperty> and <jsp:setProperty> ), nested names (a property named address.city returns the value retrieved by the Java expression getAddress().getCity() ), and indexed names (a property named address[3] retrieves the fourth address from the indexed &quot;address&quot; property of a bean).
      • Bean Creation - New JSP beans, in any scope, can be created from a variety of objects and APIs associated with the current request, or with the servlet container in which this page is running.
      • Bean Output - Supports the rendering of textual output from a bean (or bean property), which will be included in the response being created by your JSP page.
  • 53. Bean Tags   Tag Name Description cookie Define a scripting variable based on the value(s) of the specified request cookie. define Define a scripting variable based on the value(s) of the specified bean property. header Define a scripting variable based on the value(s) of the specified request header. include Load the response from a dynamic application request and make it available as a bean. message Render an internationalized message string to the response. page Expose a specified item from the page context as a bean. parameter Define a scripting variable based on the value(s) of the specified request parameter. resource Load a web application resource and make it available as a bean. size Define a bean containing the number of elements in a Collection or Map. struts Expose a named Struts internal configuration object as a bean. write Render the value of the specified bean property to the current JspWriter.
  • 54. Bean Tag Example <table border=&quot;2&quot;> <tr> <th align=&quot;left&quot;><bean:message key=“imagebroker.lob”/></th> <th align=&quot;left&quot;><bean:message key=“imagebroker.unitnbr”/></th> <th align=&quot;left&quot;><bean:message key=“imagebroker.onbase_dns”/></th> </tr> <logic:iterate id=&quot;image&quot; property=&quot;collection&quot; name=&quot;ImageLocationListForm&quot;> <tr> <td><a href=&quot;ImageLocationListForm.do?lob=<bean:write name='image' property='lob'/> &unitnbr=<bean:write name='image' property='unitnbr'/> &onbase_dns=<bean:write name='image' property='onbase_dns'/>&quot; > <bean:write name=&quot;image&quot; property=&quot;lob&quot;/></a></td> <td><bean:write name=&quot;image&quot; property=&quot;unitnbr&quot;/></td> <td><bean:write name=&quot;image&quot; property=&quot;onbase_dns&quot;/></td> </tr> </logic:iterate> </table>
  • 55. Logic Tags
    • The 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.
  • 56. Logic Tags
    • For tags that do value comparisons ( equal , greaterEqual , greaterThan , lessEqual , lessThan , notEqual ), the following rules apply:
      • The specified value is examined. If it can be converted successfully to a double or a long , it is assumed that the ultimate comparison will be numeric (either floating point or integer). Otherwise, a String comparison will be performed.
      • The variable to be compared to is retrieved, based on the selector attribute(s) ( cookie , header , name , parameter , property ) present on this tag. It will be converted to the appropriate type for the comparison, as determined above.
      • A request time exception will be thrown if the specified variable cannot be retrieved, or has a null value.
      • The specific comparison for this tag will be performed, and the nested body content of this tag will be evaluated if the comparison returns a true result.
  • 57. Logic Tags
    • For tags that do substring matching ( match , notMatch ), the following rules apply:
      • The specified variable is retrieved, based on the selector attribute(s) ( cookie , header , name , parameter , property ) present on this tag. The variable is converted to a String, if necessary.
      • A request time exception will be thrown if the specified variable cannot be retrieved, or has a null value.
      • The specified value is checked for existence as a substring of the variable, in the position specified by the location attribute, as follows: at the beginning (if location is set to start ), at the end (if location is set to end ), or anywhere (if location is not specified).
  • 58. Logic Tags   Tag Name Description empty Evaluate the nested body content of this tag if the requested variable is either null or an empty string. equal Evaluate the nested body content of this tag if the requested variable is equal to the specified value. forward Forward control to the page specified by the specified ActionForward entry. greaterEqual Evaluate the nested body content of this tag if requested variable is greater than or equal to specified value. greaterThan Evaluate the nested body content of this tag if the requested variable is greater than the specified value. iterate Repeat the nested body content of this tag over a specified collection. lessEqual Evaluate the nested body content of this tag if requested variable is greater than or equal to specified value. lessThan Evaluate the nested body content of this tag if the requested variable is less than the specified value. match Evaluate the nested body content of this tag if specified value is an appropriate substring of requested variable. messagesNotPresent Generate the nested body content of this tag if the specified message is not present in this request. messagesPresent Generate the nested body content of this tag if the specified message is present in this request. notEmpty Evaluate the nested body content of this tag if the requested variable is neither null nor an empty string. notEqual Evaluate the nested body content of this tag if the requested variable is not equal to the specified value. notMatch Evaluate the nested body content of tag if specified value not an appropriate substring of requested variable. notPresent Generate the nested body content of this tag if the specified value is not present in this request. present Generate the nested body content of this tag if the specified value is present in this request. redirect Render an HTTP Redirect
  • 59. Logic Tags - Example <html:html> <head> <title><bean:message key=&quot;imagebrokerlink.title&quot;/></title> <META name=&quot;GENERATOR&quot; content=&quot;IBM WebSphere Studio&quot;> </head> <body> <html:form action=&quot;/ImageLocationForm&quot; > <center> <font size=3> <br> <b> <logic:notEqual property=&quot;action&quot; name=&quot;ImageLocationForm&quot; value=&quot;Insert&quot;> <bean:message key=&quot;imagelocationdetail.title&quot;/> </logic:notEqual> <logic:equal property=&quot;action&quot; name=&quot;ImageLocationForm&quot; value=&quot;Insert&quot;> <bean:message key=&quot;imagelocationinsert.title&quot;/> </logic:equal> … …
  • 60. Template Tags
    • The Template tag library contains three tags: put, get, and insert. Put tags put content into request scope, which is retrieved by a get tag in a different JSP page (the template). That template is included with the insert tag.
  • 61. Template Tags
    • Insert Inserts (includes, actually) a template. Templates are JSP pages that include parameterized content. That content comes from put tags that are children of insert tags.
    • Put Puts content into request scope.
    • Get Gets the content from request scope that was put there by a put tag.
  • 62. Custom Tags <%@ taglib uri=&quot;WEB-INF/imagebroker.tld&quot; prefix=&quot;broker&quot; %> <table width=750 cellspacing=0 cellpadding=2 border=2 > <tr> <td><broker:form lob='<%=test.getLob()%>' unitnbr='<%=test.getUnitnbr()%>' userid='<%=test.getUserid()%>' > <broker:doctype value=&quot;Invoice&quot;/> <broker:keyword name=&quot;CompanyNbr&quot; value=&quot;55555&quot;/> <broker:keyword name=&quot;PONbr&quot; value=&quot;M12345&quot;/> <broker:constraint name=&quot;FromDate&quot; value=&quot;02/02/2002&quot;/> <broker:constraint name=&quot;ToDate&quot; value=&quot;02/28/2002&quot;/> Image Broker Link Test </broker:form> </td> </tr> </table>
  • 63. Custom Tags – tld File <tag> <name>doctype</name> <tagclass>com.pri.brokertag.ImageBrokerDoctype</tagclass> <attribute> <name>value</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
  • 64. Custom Tags – Tag Class public class ImageBrokerDoctype extends TagSupport { private String value = null; public int doStartTag() throws JspException { Hashtable ht = null; String keyword_count = null; int iCnt = 0; HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); ht = (Hashtable) request.getAttribute(&quot;keyword_parms&quot;); keyword_count = (String) request.getAttribute(&quot;queryobject_count&quot;); iCnt ++; ht.put(&quot;QueryObject&quot; + iCnt, value); request.setAttribute(&quot;keyword_parms&quot;, ht); request.setAttribute(&quot;queryobject_count&quot;, new String(new Integer(iCnt).toString())); return EVAL_PAGE; } }
  • 65. STRUTS Configuration File Unit 6
  • 66. STRUTS Configuration File
    • The developer's responsibility is to create an XML file named struts-config.xml , and place it in the WEB-INF directory of your application. This format of this document is constrained by it's definition in &quot;struts-config_1_0.dtd&quot;. The outermost XML element must be <struts-config> .
  • 67. STRUTS Configuration File
    • Inside of the <struts-config> element, there are two important elements that are used to describe your actions:
    • <form-beans> This section contains your form bean definitions. You use a <form-bean> element for each form bean, which has the following important attributes:
      • name : A unique identifier for this bean, which will be used to reference it in corresponding action mappings. Usually, this is also the name of the request or session attribute under which this form bean will be stored.
      • type : The fully-qualified Java classname of your form bean.
    • <action-mappings> This section contains your action definitions. You use an <action> element for each of your actions you would like to define. Each action element requires the following attributes to be defined:
      • path : The application context-relative path to the action
      • type : The fully qualified java classname of your Action class
      • name : The name of your <form-bean> element to use with this action
  • 68. Struts-config.xml <?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot; ?> <!DOCTYPE struts-config PUBLIC &quot;-//Apache Software Foundation//DTD Struts Configuration 1.0//EN&quot; &quot;http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd&quot;> <struts-config> <!-- ========== Form Bean Definitions =================================== --> <form-beans> <form-bean name=&quot;CryptForm&quot; type=&quot;com.pri.imagebrokerWeb.CryptForm&quot; /> </form-beans> <!-- ========== Global Forward Definitions ============================== --> <global-forwards> <forward name=&quot;start&quot; path=&quot;/index.html&quot;/> </global-forwards> <!-- ========== Action Mapping Definitions ============================== --> <action-mappings> <action path=&quot;/CryptForm&quot; type=&quot;com.pri.imagebrokerWeb.CryptAction&quot; name=&quot;CryptForm&quot; scope=&quot;request&quot; input=&quot;/pgCrypt.jsp&quot;> <forward name=&quot;encrypt&quot; path=&quot;/pgCryptDisplay.jsp&quot;/> </action> </action-mappings> </struts-config>
  • 69. Web Application Descriptor File Unit 7
  • 70. Web.xml File
    • The final step in setting up the application is to configure the application deployment descriptor (stored in file WEB-INF/web.xml ) to include all the Struts components that are required. Using the deployment descriptor for the example application as a guide, we see that the following entries need to be created or modified.
  • 71. Web.xml File <?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?> <!DOCTYPE web-app PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN&quot; &quot;http://java.sun.com/j2ee/dtds/web-app_2_2.dtd&quot;> <web-app id=&quot;WebApp&quot;> <display-name>imagebrokerWeb</display-name> <!-- Action Servlet Configuration --> <servlet id=&quot;Servlet_1&quot;> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>application</param-name><param-value>imagebrokerWeb</param-value> </init-param> <init-param> <param-name>config</param-name><param-value>WEB-INF/struts-config.xml</param-value> </init-param> </servlet>
  • 72. Web.xml File - continued <!-- Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- The Welcome File List --> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list>
  • 73. Web.xml File - continued <!-- Struts Tag Library Descriptors --> <taglib> <taglib-uri>WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> <taglib> <taglib-uri>WEB-INF/struts-html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> <taglib> <taglib-uri>WEB-INF/struts-logic.tld</taglib-uri> <taglib-location>/WEB-INF/struts-logic.tld</taglib-location> </taglib> </web-app>
  • 74. Application Resources File Unit 8
  • 75. Application.properties File error.cryptvalue.required=<li>You must enter some text.</li> error.lob.required=<li>You must enter the Line of Business.</li> error.unitnbr.required=<li>You must enter the Unit Number.</li> error.onbase_dns.required=<li>You must enter the OnBase DNS.</li> imagebroker.linkname=Project Refinery, Inc. imagebroker.title=pri Image Broker imagebrokerlink.title=pri Image Broker Link Test imagelocationlist.title=Image Location List imagelocationdetail.title=Image Location Detail imagelocationinsert.title=Image Location Insert errors.header= errors.footer=
  • 76. Resources Unit 9
  • 77. Resources
    • Main Struts Web Site
      • http://jakarta.apache.org/struts/index.html
    • Struts User Guide
      • http://jakarta.apache.org/struts/userGuide/index.html
    • Various Struts Resources
      • http://jakarta.apache.org/struts/resources.html
    • Ted Husted Web Site
      • http://www.husted.com/struts/