Professional Documents
Culture Documents
Jakarta Struts: Twincling
Jakarta Struts: Twincling
freedom of innovation
Jakarta Struts
An Apache Software Foundation Project
Servlets
Replaces CGI Single heavy weight process multiple lightweight threads Availability of entire Java API Hard-coding HTML Internationalization overhead
JavaServer Pages
Combination of static HTML, XML like tags and scriptlets Compiled Support for scripting and access to Java API Extended through use of custom tags
Overview
Model-View-Controller Design Pattern Model Components View Components Controller Components Tag Libraries STRUTS Configuration File Web Application Descriptor File Application Resources File Resources
Controller bundles and routes HTTP request to other objects in framework Controller parses configuration file
Configuration file contains action mappings (determines navigation) Controller uses mappings to turn HTTP requests into application actions Mapping must specify
A request path Object type to act upon the request
Model Components
Model divided into concepts
Internal state of the system Actions that can change that state
Model Components
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
Model Components
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
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
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 "name=value" 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
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 "xx
<%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <html:html> <head> <title> <bean:message key="logon.title"/> </title> <body bgcolor="white"> <html:errors/> <html:form action=/logonpath.do"> <table border="0" width="100%"> <tr> <th align="right"> <html:message key="prompt.username"/> </th> <td align="left"> <html:text property="username" size="16"/> </td> </tr> <tr> <td align="right"> <html:submit> <bean:message key="button.submit"/> </html:submit> </td>
View Components
Controller Components
Struts includes a Servlet that implements the primary function of mapping a request URI to an Action class (ActionServlet)
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;
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
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
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 threadsafe coding is to use only local variables, not instance variables, in your Action class
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
<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
<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
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="false" description="Example Data Source Description" driverClass="org.postgresql.Driver" maxCount="4" minCount="2" password="mypassword" url="jdbc:postgresql://localhost/mydatabase" user="myusername"/> </data-sources> </struts-config>
Tag Libraries
HTML Tags Bean Tags Logic Tags Template Tags Custom 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.
HTML Tags
HTML "form" tags
button cancel checkboxes file hidden image multibox password input fields radio buttons reset buttons
<HTML:HTML> <BODY> <HTML:FORM Action="/CustomerForm" focus=name > <TABLE WIDTH="100%"> <TR><TD><bean:message key="customer.name"/></TD> <TD><HTML:TEXT property="name" size="40" maxlength="40" /></TD></TR> <TR><TD><bean:message key="customer.address"/></TD> <TD><HTML:TEXT property="address" size ="40" maxlength ="40" /></TD></TR> <TR><TD><bean:message key="customer.city"/></TD> <TD><HTML:TEXT property="city" size ="20" maxlength ="20" /></TD></TR> <TR><TD><bean:message key="customer.state"/></TD> <TD><HTML:TEXT property="state" size ="2" maxlength ="2" /></TD></TR> <TR><TD><bean:message key="customer.zip"/></TD> <TD><HTML:TEXT property="zip" size ="9" maxlength ="9" /></TD></TR> <TR><TD ALIGN=CENTER><html:submit property="action" value ="Save"/></TD> <TD><html:reset property="action" value ="Reset"/></TD></TR> </TABLE> </HTML:FORM> </BODY> </HTML:HTML>
Bean Tags
The "struts-bean" 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 "address" 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.
Tag Name cookie define header include message page parameter resource size struts write
Description Define a scripting variable based on the value(s) of the specified request cookie. Define a scripting variable based on the value(s) of the specified bean property. Define a scripting variable based on the value(s) of the specified request header. Load the response from a dynamic application request and make it available as a bean. Render an internationalized message string to the response. Expose a specified item from the page context as a bean. Define a scripting variable based on the value(s) of the specified request parameter. Load a web application resource and make it available as a bean. Define a bean containing the number of elements in a Collection or Map. Expose a named Struts internal configuration object as a bean. Render the value of the specified bean property to the current JspWriter.
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. Can do value comparison, substring matching, etc
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.
Custom Tags
<%@ taglib uri="WEB-INF/imagebroker.tld" prefix="broker" %> <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="Invoice"/> <broker:keyword name="CompanyNbr" value="55555"/> <broker:keyword name="PONbr" value="M12345"/> <broker:constraint name="FromDate" value="02/02/2002"/> <broker:constraint name="ToDate" value="02/28/2002"/> Image Broker Link Test </broker:form> </td> </tr> </table>
STRUTS Configuration File The developer's responsibility is to create an XML file named strutsconfig.xml, and place it in the WEB-INF directory of your application. This format of this document is constrained by it's definition in "struts-config_1_0.dtd". The outermost XML element must be <struts-config>.
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 <formbean> 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
Struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd"> <struts-config> <!-- ========== Form Bean Definitions =================================== --> <form-beans> <form-bean name="CryptForm" type="com.pri.imagebrokerWeb.CryptForm" /> </form-beans> <!-- ========== Global Forward Definitions ============================== --> <global-forwards> <forward name="start" path="/index.html"/> </global-forwards> <!-- ========== Action Mapping Definitions ============================== --> <action-mappings> <action path="/CryptForm" type="com.pri.imagebrokerWeb.CryptAction" name="CryptForm" scope="request" input="/pgCrypt.jsp"> <forward name="encrypt" path="/pgCryptDisplay.jsp"/> </action> </action-mappings> </struts-config>
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.
web.xml File
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app id="WebApp"> <display-name>imagebrokerWeb</display-name> <!-- Action Servlet Configuration --> <servlet id="Servlet_1"> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>application</param-name><param-value>imagebrokerWeb</paramvalue> </init-param> <init-param> <param-name>config</param-name><param-value>WEB-INF/strutsconfig.xml</param-value> </init-param> </servlet>
Resources
Jakarta Struts Web Site http://jakarta.apache.org/struts/index.htm Struts Community Resources http://struts.sourceforge.net/community/tutorials.html Learn Technology http://www.learntechnology.net/ Demystifying Jakarta Struts http://www.coreservlets.com/Apache-Struts-Tutorial/
Books
Chuck Cavaness
James Holmes
Books
Ted Husted
Special thanks
AppLabs Technologies Pvt. Ltd. Coordinating for TWINCLING Saturday Meet (TSM) Providing LCD projector and Meeting space. http://www.applabs.com/
About Us
India's first, independent, "not-for-profit", OpenSource software development & promotion society. www.twincling.org groups.yahoo.com/group/twincling