SlideShare ist ein Scribd-Unternehmen logo
1 von 77
Project Refinery, Inc. 1
STRUTSPart of the Jakarta Project
Sponsored by the
Apache Software Foundation
Developed by: Roger W Barnes of Project Refinery, Inc.
Introduction to Struts
Project Refinery, Inc. 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
Project Refinery, Inc. 3
STRUTS Objectives
 Unit 6 - STRUTS Configuration File
 Unit 7 - Web Application Descriptor File
 Unit 8 - Application Resources File
 Unit 9 – Resources
Project Refinery, Inc. 4
Model-View-Controller Design
Pattern
Unit 1
Project Refinery, Inc. 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
Project Refinery, Inc. 6
STRUTS MVC Design Pattern
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 9
Model Components
Unit 2
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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 "stub"
method, and provide error messages in the
standard application resource, Struts will
automatically validate the input from the form
Project Refinery, Inc. 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 "customer" bean on your Action Form, and
then refer to the property "customer.name" in your
JSP view. This would correspond to the methods
customer.getName() and
customer.setName(string Name) on your
customer bean
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 17
STRUTS Model Components
 Business Logic Beans - Continued
 For larger applications, these beans will
often be stateful or stateless Enterprise
JavaBeans (EJBs)
Project Refinery, Inc. 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
Project Refinery, Inc. 19
View Components
Unit 3
Project Refinery, Inc. 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 "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
Project Refinery, Inc. 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 "xx"
Project Refinery, Inc. 22
STRUTS View Components
 Forms and FormBean interactions
 HTML Forms and their limitations
 Errors not easily handled
Project Refinery, Inc. 23
STRUTS View Components
<%@ 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>
Project Refinery, Inc. 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
Project Refinery, Inc. 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 "text“
 The submit and reset tags generate the
corresponding buttons at the bottom of the form
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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 "src" and "lowsrc" 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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="xxxxx" %> directive can include a
file that contains java code or jsp tags
 The include action (<jsp:include page="xxxxx"
flush="true" />) is processed at request time, and is
handled transparently by the server
 The bean:include tag takes either a an argument
"forward" representing a logical name mapped to the jsp
to include, or the "id" argument, which represents a page
context String variable to print out to the jsp page
Project Refinery, Inc. 32
Controller Components
Unit 4
Project Refinery, Inc. 33
STRUTS Controller Components
 Struts includes a Servlet that
implements the primary function of
mapping a request URI to an Action
class (ActionServlet)
Project Refinery, Inc. 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
Project Refinery, Inc. 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;
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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.
Project Refinery, Inc. 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:
Project Refinery, Inc. 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
Project Refinery, Inc. 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
Project Refinery, Inc. 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="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>
Project Refinery, Inc. 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
Project Refinery, Inc. 46
Tag Libraries
Unit 5
Project Refinery, Inc. 47
STRUTS Tag Libraries
 HTML Tags
 Bean Tags
 Logic Tags
 Template Tags
 Custom Tags
Project Refinery, Inc. 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.
Project Refinery, Inc. 49
HTML Tags
 HTML "form" tags
 button
 cancel
 checkboxes
 file
 hidden
 image
 multibox
 password input fields
 radio buttons
 reset buttons
 HTML "form" tags
 select lists with
embedded
 option
 options
 submit buttons
 text input fields
 textareas
Project Refinery, Inc. 50
HTML Tags – Typical HTML Form
<HTML>
<BODY>
<FORM>
<TABLE WIDTH="100%">
<TR><TD>First Name</TD>
<TD><INPUT TYPE="TEXT" NAME="Name" SIZE="40" MAXLENGTH="40"></TD></TR>
<TR><TD>Street Address</TD>
<TD><INPUT TYPE="TEXT" NAME="Address" SIZE="40" MAXLENGTH="40"></TD></TR>
<TR><TD>City</TD>
<TD><INPUT TYPE="TEXT" NAME="City" SIZE="20" MAXLENGTH="20"></TD></TR>
<TR><TD>State</TD>
<TD><INPUT TYPE="TEXT" NAME="State" SIZE="2" MAXLENGTH="2"></TD></TR>
<TR><TD>Postal Code</TD>
<TD><INPUT TYPE="TEXT" NAME="ZipCode" SIZE="9" MAXLENGTH="9"></TD></TR>
<TR><TD ALIGN=CENTER><INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Save"></TD>
<TD><INPUT TYPE="RESET" NAME="Reset" VALUE="Cancel"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>
Project Refinery, Inc. 51
HTML Tags – Typical Struts Form
<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>
Project Refinery, Inc. 52
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.
Project Refinery, Inc. 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.
Project Refinery, Inc. 54
Bean Tag Example
<table border="2">
<tr>
<th align="left"><bean:message key=“imagebroker.lob”/></th>
<th align="left"><bean:message key=“imagebroker.unitnbr”/></th>
<th align="left"><bean:message key=“imagebroker.onbase_dns”/></th>
</tr>
<logic:iterate id="image" property="collection"
name="ImageLocationListForm">
<tr>
<td><a href="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'/>" >
<bean:write name="image" property="lob"/></a></td>
<td><bean:write name="image" property="unitnbr"/></td>
<td><bean:write name="image" property="onbase_dns"/></td>
</tr>
</logic:iterate>
Project Refinery, Inc. 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.
Project Refinery, Inc. 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.
Project Refinery, Inc. 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).
Project Refinery, Inc. 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
Project Refinery, Inc. 59
Logic Tags - Example
<html:html>
<head>
<title><bean:message key="imagebrokerlink.title"/></title>
<META name="GENERATOR" content="IBM WebSphere Studio">
</head>
<body>
<html:form action="/ImageLocationForm" >
<center>
<font size=3>
<br>
<b>
<logic:notEqual property="action" name="ImageLocationForm" value="Insert">
<bean:message key="imagelocationdetail.title"/>
</logic:notEqual>
<logic:equal property="action" name="ImageLocationForm" value="Insert">
<bean:message key="imagelocationinsert.title"/>
</logic:equal>
…
…
Project Refinery, Inc. 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.
Project Refinery, Inc. 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.
Project Refinery, Inc. 62
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>
Project Refinery, Inc. 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>
Project Refinery, Inc. 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("keyword_parms");
keyword_count = (String)
request.getAttribute("queryobject_count");
iCnt ++;
ht.put("QueryObject" + iCnt, value);
request.setAttribute("keyword_parms", ht);
request.setAttribute("queryobject_count", new String(new
Integer(iCnt).toString()));
return EVAL_PAGE; }
}
Project Refinery, Inc. 65
STRUTS Configuration File
Unit 6
Project Refinery, Inc. 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 "struts-config_1_0.dtd". The
outermost XML element must be
<struts-config>.
Project Refinery, Inc. 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
Project Refinery, Inc. 68
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>
Project Refinery, Inc. 69
Web Application Descriptor
File
Unit 7
Project Refinery, Inc. 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.
Project Refinery, Inc. 71
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</param-
value>
</init-param>
<init-param>
<param-name>config</param-name><param-value>WEB-INF/struts-
config.xml</param-value>
</init-param>
</servlet>
Project Refinery, Inc. 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>
Project Refinery, Inc. 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>
Project Refinery, Inc. 74
Application Resources File
Unit 8
Project Refinery, Inc. 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=
Project Refinery, Inc. 76
Resources
Unit 9
Project Refinery, Inc. 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/

Weitere ähnliche Inhalte

Was ist angesagt?

Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
JSF basics
JSF basicsJSF basics
JSF basicsairbo
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkGuo Albert
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
Java server faces
Java server facesJava server faces
Java server facesowli93
 
Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSFSoftServe
 
Sun JSF Presentation
Sun JSF PresentationSun JSF Presentation
Sun JSF PresentationGaurav Dighe
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
9. java server faces
9. java server faces9. java server faces
9. java server facesAnusAhmad
 

Was ist angesagt? (20)

Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Introduction to jsf 2
Introduction to jsf 2Introduction to jsf 2
Introduction to jsf 2
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Java server faces
Java server facesJava server faces
Java server faces
 
JSF basics
JSF basicsJSF basics
JSF basics
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Java server faces
Java server facesJava server faces
Java server faces
 
Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSF
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Jsf2.0 -4
Jsf2.0 -4Jsf2.0 -4
Jsf2.0 -4
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
 
Jsf
JsfJsf
Jsf
 
Sun JSF Presentation
Sun JSF PresentationSun JSF Presentation
Sun JSF Presentation
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
 
Struts Ppt 1
Struts Ppt 1Struts Ppt 1
Struts Ppt 1
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
9. java server faces
9. java server faces9. java server faces
9. java server faces
 

Andere mochten auch

Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts weili_at_slideshare
 
Step by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts ApplicationStep by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts Applicationelliando dias
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppSyed Shahul
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkMohit Belwal
 

Andere mochten auch (8)

Introduction to Struts 2
Introduction to Struts 2Introduction to Struts 2
Introduction to Struts 2
 
Frameworks in java
Frameworks in javaFrameworks in java
Frameworks in java
 
Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts
 
Step by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts ApplicationStep by Step Guide for building a simple Struts Application
Step by Step Guide for building a simple Struts Application
 
Struts Basics
Struts BasicsStruts Basics
Struts Basics
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts App
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 

Ähnlich wie Struts Framework Introduction and MVC Design Pattern

Struts Intro Course(1)
Struts Intro Course(1)Struts Intro Course(1)
Struts Intro Course(1)wangjiaz
 
Tuning and optimizing webcenter spaces application white paper
Tuning and optimizing webcenter spaces application white paperTuning and optimizing webcenter spaces application white paper
Tuning and optimizing webcenter spaces application white paperVinay Kumar
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Zsang nguyen
 
Architecture Specification - Visual Modeling Tool
Architecture Specification - Visual Modeling ToolArchitecture Specification - Visual Modeling Tool
Architecture Specification - Visual Modeling ToolAdriaan Venter
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
Apachecon 2002 Struts
Apachecon 2002 StrutsApachecon 2002 Struts
Apachecon 2002 Strutsyesprakash
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4than sare
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_entechbed
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2javatrainingonline
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentChui-Wen Chiu
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember Chandra Sekar
 
D22 Portlet Development With Open Source Frameworks
D22 Portlet Development With Open Source FrameworksD22 Portlet Development With Open Source Frameworks
D22 Portlet Development With Open Source FrameworksSunil Patil
 
D22 portlet development with open source frameworks
D22 portlet development with open source frameworksD22 portlet development with open source frameworks
D22 portlet development with open source frameworksSunil Patil
 
Building social and RESTful frameworks
Building social and RESTful frameworksBuilding social and RESTful frameworks
Building social and RESTful frameworksbrendonschwartz
 

Ähnlich wie Struts Framework Introduction and MVC Design Pattern (20)

Struts N E W
Struts N E WStruts N E W
Struts N E W
 
Struts Intro Course(1)
Struts Intro Course(1)Struts Intro Course(1)
Struts Intro Course(1)
 
Session 1
Session 1Session 1
Session 1
 
Tuning and optimizing webcenter spaces application white paper
Tuning and optimizing webcenter spaces application white paperTuning and optimizing webcenter spaces application white paper
Tuning and optimizing webcenter spaces application white paper
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
 
Architecture Specification - Visual Modeling Tool
Architecture Specification - Visual Modeling ToolArchitecture Specification - Visual Modeling Tool
Architecture Specification - Visual Modeling Tool
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Apachecon 2002 Struts
Apachecon 2002 StrutsApachecon 2002 Struts
Apachecon 2002 Struts
 
PDFArticle
PDFArticlePDFArticle
PDFArticle
 
MVC
MVCMVC
MVC
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_en
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember
 
D22 Portlet Development With Open Source Frameworks
D22 Portlet Development With Open Source FrameworksD22 Portlet Development With Open Source Frameworks
D22 Portlet Development With Open Source Frameworks
 
D22 portlet development with open source frameworks
D22 portlet development with open source frameworksD22 portlet development with open source frameworks
D22 portlet development with open source frameworks
 
Building social and RESTful frameworks
Building social and RESTful frameworksBuilding social and RESTful frameworks
Building social and RESTful frameworks
 

Kürzlich hochgeladen

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Kürzlich hochgeladen (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Struts Framework Introduction and MVC Design Pattern

  • 1. Project Refinery, Inc. 1 STRUTSPart of the Jakarta Project Sponsored by the Apache Software Foundation Developed by: Roger W Barnes of Project Refinery, Inc. Introduction to Struts
  • 2. Project Refinery, Inc. 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. Project Refinery, Inc. 3 STRUTS Objectives  Unit 6 - STRUTS Configuration File  Unit 7 - Web Application Descriptor File  Unit 8 - Application Resources File  Unit 9 – Resources
  • 4. Project Refinery, Inc. 4 Model-View-Controller Design Pattern Unit 1
  • 5. Project Refinery, Inc. 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. Project Refinery, Inc. 6 STRUTS MVC Design Pattern
  • 7. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 9 Model Components Unit 2
  • 10. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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 "stub" method, and provide error messages in the standard application resource, Struts will automatically validate the input from the form
  • 14. Project Refinery, Inc. 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 "customer" bean on your Action Form, and then refer to the property "customer.name" in your JSP view. This would correspond to the methods customer.getName() and customer.setName(string Name) on your customer bean
  • 15. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 17 STRUTS Model Components  Business Logic Beans - Continued  For larger applications, these beans will often be stateful or stateless Enterprise JavaBeans (EJBs)
  • 18. Project Refinery, Inc. 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. Project Refinery, Inc. 19 View Components Unit 3
  • 20. Project Refinery, Inc. 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 "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
  • 21. Project Refinery, Inc. 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 "xx"
  • 22. Project Refinery, Inc. 22 STRUTS View Components  Forms and FormBean interactions  HTML Forms and their limitations  Errors not easily handled
  • 23. Project Refinery, Inc. 23 STRUTS View Components <%@ 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>
  • 24. Project Refinery, Inc. 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. Project Refinery, Inc. 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 "text“  The submit and reset tags generate the corresponding buttons at the bottom of the form
  • 26. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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 "src" and "lowsrc" 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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="xxxxx" %> directive can include a file that contains java code or jsp tags  The include action (<jsp:include page="xxxxx" flush="true" />) is processed at request time, and is handled transparently by the server  The bean:include tag takes either a an argument "forward" representing a logical name mapped to the jsp to include, or the "id" argument, which represents a page context String variable to print out to the jsp page
  • 32. Project Refinery, Inc. 32 Controller Components Unit 4
  • 33. Project Refinery, Inc. 33 STRUTS Controller Components  Struts includes a Servlet that implements the primary function of mapping a request URI to an Action class (ActionServlet)
  • 34. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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="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>
  • 45. Project Refinery, Inc. 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. Project Refinery, Inc. 46 Tag Libraries Unit 5
  • 47. Project Refinery, Inc. 47 STRUTS Tag Libraries  HTML Tags  Bean Tags  Logic Tags  Template Tags  Custom Tags
  • 48. Project Refinery, Inc. 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. Project Refinery, Inc. 49 HTML Tags  HTML "form" tags  button  cancel  checkboxes  file  hidden  image  multibox  password input fields  radio buttons  reset buttons  HTML "form" tags  select lists with embedded  option  options  submit buttons  text input fields  textareas
  • 50. Project Refinery, Inc. 50 HTML Tags – Typical HTML Form <HTML> <BODY> <FORM> <TABLE WIDTH="100%"> <TR><TD>First Name</TD> <TD><INPUT TYPE="TEXT" NAME="Name" SIZE="40" MAXLENGTH="40"></TD></TR> <TR><TD>Street Address</TD> <TD><INPUT TYPE="TEXT" NAME="Address" SIZE="40" MAXLENGTH="40"></TD></TR> <TR><TD>City</TD> <TD><INPUT TYPE="TEXT" NAME="City" SIZE="20" MAXLENGTH="20"></TD></TR> <TR><TD>State</TD> <TD><INPUT TYPE="TEXT" NAME="State" SIZE="2" MAXLENGTH="2"></TD></TR> <TR><TD>Postal Code</TD> <TD><INPUT TYPE="TEXT" NAME="ZipCode" SIZE="9" MAXLENGTH="9"></TD></TR> <TR><TD ALIGN=CENTER><INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Save"></TD> <TD><INPUT TYPE="RESET" NAME="Reset" VALUE="Cancel"></TD></TR> </TABLE> </FORM> </BODY> </HTML>
  • 51. Project Refinery, Inc. 51 HTML Tags – Typical Struts Form <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>
  • 52. Project Refinery, Inc. 52 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.
  • 53. Project Refinery, Inc. 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. Project Refinery, Inc. 54 Bean Tag Example <table border="2"> <tr> <th align="left"><bean:message key=“imagebroker.lob”/></th> <th align="left"><bean:message key=“imagebroker.unitnbr”/></th> <th align="left"><bean:message key=“imagebroker.onbase_dns”/></th> </tr> <logic:iterate id="image" property="collection" name="ImageLocationListForm"> <tr> <td><a href="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'/>" > <bean:write name="image" property="lob"/></a></td> <td><bean:write name="image" property="unitnbr"/></td> <td><bean:write name="image" property="onbase_dns"/></td> </tr> </logic:iterate>
  • 55. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 59 Logic Tags - Example <html:html> <head> <title><bean:message key="imagebrokerlink.title"/></title> <META name="GENERATOR" content="IBM WebSphere Studio"> </head> <body> <html:form action="/ImageLocationForm" > <center> <font size=3> <br> <b> <logic:notEqual property="action" name="ImageLocationForm" value="Insert"> <bean:message key="imagelocationdetail.title"/> </logic:notEqual> <logic:equal property="action" name="ImageLocationForm" value="Insert"> <bean:message key="imagelocationinsert.title"/> </logic:equal> … …
  • 60. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 62 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>
  • 63. Project Refinery, Inc. 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. Project Refinery, Inc. 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("keyword_parms"); keyword_count = (String) request.getAttribute("queryobject_count"); iCnt ++; ht.put("QueryObject" + iCnt, value); request.setAttribute("keyword_parms", ht); request.setAttribute("queryobject_count", new String(new Integer(iCnt).toString())); return EVAL_PAGE; } }
  • 65. Project Refinery, Inc. 65 STRUTS Configuration File Unit 6
  • 66. Project Refinery, Inc. 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 "struts-config_1_0.dtd". The outermost XML element must be <struts-config>.
  • 67. Project Refinery, Inc. 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. Project Refinery, Inc. 68 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>
  • 69. Project Refinery, Inc. 69 Web Application Descriptor File Unit 7
  • 70. Project Refinery, Inc. 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. Project Refinery, Inc. 71 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</param- value> </init-param> <init-param> <param-name>config</param-name><param-value>WEB-INF/struts- config.xml</param-value> </init-param> </servlet>
  • 72. Project Refinery, Inc. 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. Project Refinery, Inc. 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. Project Refinery, Inc. 74 Application Resources File Unit 8
  • 75. Project Refinery, Inc. 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. Project Refinery, Inc. 76 Resources Unit 9
  • 77. Project Refinery, Inc. 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/

Hinweis der Redaktion

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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&amp;apos;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.
  6. 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).
  7. Within a web-based application, JavaBeans can be stored in (and accessed from) a number of different collections of &amp;quot;attributes&amp;quot;. 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):
  8. You should note that a &amp;quot;form&amp;quot;, 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 &amp;quot;form&amp;quot; (from the user&amp;apos;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.
  9. 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.
  10. 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.
  11. 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&amp;apos;s memory as needed. Entity Enterprise JavaBeans are also used for this purpose in large scale applications.
  12. 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.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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. &amp;lt;servlet&amp;gt; &amp;lt;servlet-name&amp;gt;action&amp;lt;/servlet-name&amp;gt; &amp;lt;servlet-class&amp;gt;org.apache.struts.action.ActionServlet&amp;lt;/servlet-class&amp;gt; &amp;lt;init-param&amp;gt; &amp;lt;param-name&amp;gt;application&amp;lt;/param-name&amp;gt; &amp;lt;param-value&amp;gt;MyResources&amp;lt;/param-value&amp;gt; &amp;lt;/init-param&amp;gt; &amp;lt;.../&amp;gt; &amp;lt;/servlet&amp;gt;
  18. At one time or another, most web developers have built forms using the standard capabilities of HTML, such as the &amp;lt;input&amp;gt; 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): &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;username&amp;quot; value=&amp;quot;&amp;lt;%= loginBean.getUsername() %&amp;gt;&amp;quot;/&amp;gt; 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: &amp;lt;html:text property=&amp;quot;username&amp;quot;/&amp;gt; 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 &amp;lt;input type=&amp;quot;file&amp;quot;&amp;gt; element, that generates a file browse button, but it&amp;apos;s up to the developer to handle the incoming files. Struts handles these &amp;quot;multipart&amp;quot; forms in a way identical to building normal forms.
  19. 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.
  20. 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.
  21. Within the &amp;lt;form-beans&amp;gt; section in the struts-config.xml file, you would define a form tag like the following: &amp;lt;form-bean name=&amp;quot;CustomerFormBean&amp;quot; type=&amp;quot;com.pri.javaTraining.CustomerForm&amp;quot; /&amp;gt; This &amp;lt;form-bean&amp;gt; tag is also referenced within the &amp;lt;action-mappings&amp;gt; tag in the struts-config.xml file, like the following: &amp;lt;action path=&amp;quot;/CustomerAction&amp;quot; type=&amp;quot;com.pri.javaTraining.CustomerAction&amp;quot; name=&amp;quot;CustomerFormBean&amp;quot; scope=&amp;quot;request&amp;quot; input=&amp;quot;/pgcustomer.jsp&amp;quot;&amp;gt; &amp;lt;forward name=&amp;quot;Save&amp;quot; path=&amp;quot;/pgindex.jsp&amp;quot;/&amp;gt; &amp;lt;forward name=&amp;quot;Add Account&amp;quot; path=&amp;quot;/pgaddaccount.jsp&amp;quot;/&amp;gt; &amp;lt;forward name=&amp;quot;Cancel&amp;quot; path=&amp;quot;/pgindex.jsp&amp;quot;/&amp;gt; &amp;lt;/action&amp;gt;
  22. 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 &amp;quot;field&amp;quot; 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.
  23. Below is an example of using both the &amp;lt;logic:present&amp;gt; and &amp;lt;logic:iterate&amp;gt; tags. The &amp;lt;logic:present&amp;gt; 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 &amp;lt;jsp:useBean&amp;gt; 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 &amp;lt;iterate&amp;gt; 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 &amp;lt;logic:iterate&amp;gt; tag the id attribute is named “aAccount”. This is then referenced within the &amp;lt;bean:write&amp;gt; tag by specifying a name attribute with the same value. The property attribute within the &amp;lt;bean:write&amp;gt; tag is used to call the appropriate method on whatever class that is within the Vector (or other Collection type class). &amp;lt;jsp:useBean id=&amp;quot;CustSessionBean&amp;quot; scope=&amp;quot;session&amp;quot; class=&amp;quot;com.pri.javaTraining.SessionBean&amp;quot;/&amp;gt; &amp;lt;logic:present name=&amp;quot;CustSessionBean&amp;quot; property=&amp;quot;currentCustomerAccounts&amp;quot;&amp;gt; &amp;lt;logic:iterate id=&amp;quot;aAccount&amp;quot; name=&amp;quot;CustSessionBean&amp;quot; property=&amp;quot;currentCustomerAccounts&amp;quot;&amp;gt; &amp;lt;TR&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;bean:write name=&amp;quot;aAccount&amp;quot; property=&amp;quot;accountNo&amp;quot;/&amp;gt;&amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;bean:write name=&amp;quot;aAccount&amp;quot; property=&amp;quot;accountTypeString&amp;quot;/&amp;gt;&amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;bean:write name=&amp;quot;aAccount&amp;quot; property=&amp;quot;statusCode&amp;quot;/&amp;gt;&amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;bean:write name=&amp;quot;aAccount&amp;quot; property=&amp;quot;balance&amp;quot;/&amp;gt;&amp;lt;/TD&amp;gt; &amp;lt;TD&amp;gt;&amp;lt;bean:write name=&amp;quot;aAccount&amp;quot; property=&amp;quot;openDateFormatted&amp;quot;/&amp;gt; &amp;lt;/TR&amp;gt; &amp;lt;/logic:iterate&amp;gt; &amp;lt;/logic:present&amp;gt;
  24. 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.
  25. 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&amp;apos;s, which are classes that contain the error message keys (into the application&amp;apos;s MessageResources bundle) that should be displayed. The controller servlet will store this array as a request attribute suitable for use by the &amp;lt;html:errors&amp;gt; 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 &amp;quot;business logic&amp;quot; validation from the Action.
  26. Another approach to this would be to use the Struts Template Tag library.
  27. 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.
  28. 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.
  29. 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.
  30. 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.
  31. The second method is the one used by WebSphere.
  32. 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: &amp;lt;action path=&amp;quot;/CustomerAction&amp;quot; type=&amp;quot;com.pri.javaTraining.CustomerAction&amp;quot; name=&amp;quot;CustomerFormBean&amp;quot; scope=&amp;quot;request&amp;quot; input=&amp;quot;/pgcustomer.jsp&amp;quot;&amp;gt; &amp;lt;forward name=&amp;quot;Save&amp;quot; path=&amp;quot;/pgindex.jsp&amp;quot;/&amp;gt; &amp;lt;forward name=&amp;quot;Add Account&amp;quot; path=&amp;quot;/pgaddaccount.jsp&amp;quot;/&amp;gt; &amp;lt;forward name=&amp;quot;Cancel&amp;quot; path=&amp;quot;/pgindex.jsp&amp;quot;/&amp;gt;
  33. 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)); }
  34. Only define variables within the perform() method, or within methods that you’ve added to the Action class.
  35. 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
  36. Below is an example of an ActionMapping implementation: &amp;lt;action path=&amp;quot;/CustomerAction&amp;quot; type=&amp;quot;com.pri.javaTraining.CustomerAction&amp;quot; name=&amp;quot;CustomerFormBean&amp;quot; scope=&amp;quot;request&amp;quot; input=&amp;quot;/pgcustomer.jsp&amp;quot;&amp;gt; &amp;lt;forward name=&amp;quot;Save&amp;quot; path=&amp;quot;/pgindex.jsp&amp;quot;/&amp;gt; &amp;lt;forward name=&amp;quot;Add Account&amp;quot; path=&amp;quot;/pgaddaccount.jsp&amp;quot;/&amp;gt; &amp;lt;forward name=&amp;quot;Cancel&amp;quot; path=&amp;quot;/pgindex.jsp&amp;quot;/&amp;gt;
  37. The two important elements are: &amp;lt;form-beans&amp;gt;This section contains your form bean definitions. You use a &amp;lt;form-bean&amp;gt; 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. &amp;lt;action-mappings&amp;gt;This section contains your action definitions. You use an &amp;lt;action&amp;gt; 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 &amp;lt;form-bean&amp;gt; element to use with this action
  38. Below is an example of a typical &amp;lt;form-beans&amp;gt; section: &amp;lt;form-beans&amp;gt; &amp;lt;!-- Struts Example form bean --&amp;gt; &amp;lt;form-bean name=&amp;quot;StrutsInputFormBean&amp;quot; type=&amp;quot;org.struts.example.StrutsInputForm&amp;quot; /&amp;gt; &amp;lt;form-bean name=&amp;quot;StrutsDisplayFormBean&amp;quot; type=&amp;quot;org.struts.example.StrutsDisplayForm&amp;quot; /&amp;gt; &amp;lt;/form-beans&amp;gt;
  39. Below is an example of a typical &amp;lt;action-mappings&amp;gt; section: &amp;lt;action-mappings&amp;gt; &amp;lt;!-- StrutsExample --&amp;gt; &amp;lt;action path=&amp;quot;/StrutsInputPath&amp;quot; type=&amp;quot;org.struts.example.StrutsInputAction&amp;quot; name=&amp;quot;StrutsInputFormBean&amp;quot; scope=&amp;quot;request&amp;quot; input=&amp;quot;/PgInput.jsp&amp;quot;&amp;gt; &amp;lt;forward name=&amp;quot;Next&amp;quot; path=&amp;quot;/PgDisplay.jsp&amp;quot;/&amp;gt; &amp;lt;/action&amp;gt; &amp;lt;action path=&amp;quot;/StrutsDisplayPath&amp;quot; type=&amp;quot;org.struts.example.StrutsDisplayAction&amp;quot; name=&amp;quot;StrutsDisplayFormBean&amp;quot; scope=&amp;quot;request&amp;quot; input=&amp;quot;/PgDisplay.jsp&amp;quot;&amp;gt; &amp;lt;/action&amp;gt; &amp;lt;/action-mappings&amp;gt;
  40. 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.
  41. We’re going to go over both the struts-config.xml and the web.xml files in later chapters.
  42. 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.
  43. 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.
  44. 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&amp;apos;s bean. When a field and property correspond, the bean is first used to populate the form, and then to store the user&amp;apos;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.
  45. Each of these would typically be prefixed with &amp;lt;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
  46. 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.
  47. Notice the &amp;lt;html:text tag. It’s similar to the &amp;lt;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().
  48. 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 &amp;lt;jsp:useBean&amp;gt; tag is used create a bean (if necessary), as well as a &amp;quot;scripting variable&amp;quot; that can be used within scriptlets to refer to these beans.
  49. 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.
  50. 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”.
  51. 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.
  52. For further information on the Logic Tags, visit: http://jakarta.apache.org/struts/api/org/apache/struts/taglib/logic/package-summary.html#package_description
  53. 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 &amp;quot;error page&amp;quot; in the &amp;lt;%@ page %&amp;gt; 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.
  54. For further information on the Logic Tags, visit: http://jakarta.apache.org/struts/api/org/apache/struts/taglib/logic/package-summary.html#package_description
  55. Notice the &amp;lt;logic:notEqual tag. It has a property attribute that references a getter method, a name attribute that references a form, and a value attribute that is what is going to be checked for a not equal condition. If the value is not equal to “Insert” in this example, the next line will be shown. The next line uses the bean message tag, and will display a title indicating this is a Detail page. Also notice the closing &amp;lt;/logic:notEqual&amp;gt; tag. The next line shows a &amp;lt;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.
  56. The Template library supplies tags that are useful for creating dynamic JSP templates for pages which share a common format.
  57. For further information on Template Tags, visit: http://jakarta.apache.org/struts/api/org/apache/struts/taglib/template/package-summary.html#package_description
  58. This JSP shows the use of custom tags. Note the &amp;lt;broker:form&amp;gt; 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: &amp;lt;form name=&amp;quot;ibs_form5&amp;quot; method=&amp;quot;POST&amp;quot; action=&amp;quot;http://corpiisimgdv01.pri.corpad.net/devibroker/broker_process.asp&amp;quot; target=&amp;quot;_blank&amp;quot;&amp;gt; &amp;lt;a href=javascript:document.forms.ibs_form5.submit()&amp;gt;EOBs/REMITS (via Doc Handle)&amp;lt;/a&amp;gt;&amp;lt;br&amp;gt; &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;packet&amp;quot; value=&amp;quot;E25A7C35ECBD975BCBCBED16C10EB6BE9343A40B022DC2FF774ABAD53D94293FB1780D4D4D9489B71389E0824A7B13708AEFA66BA3698DAA255A4B85741B8ECC45C0CB1F3A3261C8230FB74253AB0BC326320DFBE699B347C5CD240BA4DE1EC1A07BA20442DC9430922CE95749B6D795CF8359691F5CC91A52169FF3B6403B4D97ED09D52540E3A83B7479770300A527CA040B43F5F24CFE17D8477D856FA6106575A9F41FD95AD4D717147A9A07A45D7AE45CB22A4F6482F2BB6A1B659B725EA74FE7C59AC24D5F0069D26956144BCC54FCE5D34C15FEFBD22CEEC6E0A85D1207EBD70B8B9397ACC49A4572F0F3B5D35D559CEC9BF6ED8A94E67AAAE54DCF1D9BAD720851BCE96F0263495F0A76B65F9D1A0F9EA6454B7624DE0EEE4B9B5B69&amp;quot;&amp;gt; &amp;lt;/form&amp;gt;
  59. 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.
  60. 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.
  61. 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.
  62. The two important elements are: &amp;lt;form-beans&amp;gt;This section contains your form bean definitions. You use a &amp;lt;form-bean&amp;gt; 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. &amp;lt;action-mappings&amp;gt;This section contains your action definitions. You use an &amp;lt;action&amp;gt; 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 &amp;lt;form-bean&amp;gt; element to use with this action
  63. Notice the &amp;lt;form-beans&amp;gt; tag section. Within this section you use the &amp;lt;form-bean tag to assign a name to your form bean, and in the type attribute you put the fully qualified class name. This class is always a descendent of ActionForm. Notice the &amp;lt;global-forwards&amp;gt; tag section. Within this section you use the &amp;lt;forward tag and assign a value to the name attribute. The name attribute is referenced by the Action class to determine if the action the user performed is this name, and if so it forwards to the value specified in the path attribute. In this example if the user clicked a button where the value of the button was “start”, the user would be sent to the index.html page. Notice the &amp;lt;action-mappings&amp;gt; tag section. Within this section you use the &amp;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.
  64. 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.
  65. 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.
  66. Note the line that has the &amp;lt;servlet-class&amp;gt; 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 &amp;lt;param-name&amp;gt; tag with the value of application. The following &amp;lt;param-value&amp;gt; tag is where you reference your projects property file.
  67. Note the &amp;lt;welcome-file&amp;gt; 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: &amp;lt;servlet-mapping&amp;gt; &amp;lt;servlet-name&amp;gt;action&amp;lt;/servlet-name&amp;gt; &amp;lt;url-pattern&amp;gt;/execute/*&amp;lt;/url-pattern&amp;gt; &amp;lt;/servlet-mapping&amp;gt; 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 &amp;quot;do something&amp;quot;), the mapping entry would look like this: &amp;lt;servlet-mapping&amp;gt; &amp;lt;servlet-name&amp;gt;action&amp;lt;/servlet-name&amp;gt; &amp;lt;url-pattern&amp;gt;*.do&amp;lt;/url-pattern&amp;gt; &amp;lt;/servlet-mapping&amp;gt; and a request URI to match the /logon path described earlier might look like this: http://www.mycompany.com/myapplication/logon.do
  68. 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.
  69. Application Resource or property files are not unique to Struts applications. However, with the internationalization support built into Struts, they are used more.
  70. 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.
  71. 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.
  72. 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.