The GUI Layer: Create A Screen With Struts
The GUI Layer: Create A Screen With Struts
Model
1
JSP page handles all of the processing of the request and is also responsible for displaying the output to the client.
The client request is first intercepted by a servlet, most often referred to as a Controller Servlet. The servlet
handles the initial processing of the request and also determines which JSP page to display next.
About Struts…
- Struts is hosted by Apache Software Foundation (ASF) as part of its Jakarta Project.
- Struts is a framework based on MVC Pattern, which has mainly three components named model,
view & controller.
- It is the controller (ActionServlet), who takes the complete charge of the flow of application.
- When initialized, the controller parses a configuration file (struts-config.xml) and uses it to
deploy other control layer objects.
- The controller servlet either retrieves or creates the ActionForm bean instance, which holds the
different attributes of the HTML form.
- If the request is being used to submit an input page, the Action object can examine the data. If
necessary, the data can be sent back to the input form along with a list of messages to display on
the page.
Struts – A Model View Controller Architecture
VIEW CONTROLLER [Works as single point of access]
ActionServlet
[Responsible for <<Extends HTTPServlet>>
Presentation] 3.Forwards the request
1. Sends 2. Responsible for packaging RequestProcessor
and routing HTTP traffic to 4. Process the request
JSP [Client] Request the appropriate handler in
Components are –
for controller and
the framework.
•Custom Tags populates the form bean.
•HTML
•Java Resource Bundles 5. Sends for User 6. After validation, it
•Struts Action Forms
•Value Objects
Input Validation. delegates the
•Tiles ActionForm handling of Request to
[Form Bean] Action class
[Responsible for Validating
the user input.]
Action
13. Uses the Form Bean 11.Uses Value Object to set 7. Uses the Action Form, and
and value object for it executes the business
the attributes of Form Bean
representation. operation that is associated
12. Uses ActionMapping to decide the next view with the requested Action
through the Model.
Model
9. Performs the business operation
>
ses> Business Object
<<u
Value Object
<<
us
es
>>
Database Object
Struts – A Model View Controller Architecture
VIEW CONTROLLER [Works as single point of access]
Action
11. Uses Value Object to set
7. Uses the Action Form, and
13. Uses the Form Bean the attributes of From Bean it executes the business
and value object for operation that is associated
representation. with the requested Action
12. Uses ActionMapping to decide the next view through the Model.
Model
9. Performs the business operations
>
ses> Business Object
<<u
Value Object
<<
us
es
>>
Database Object
Why Struts / The Beauty of Struts
- One can integrate the struts components into their own framework just as they
are written in-house.
- Extending the struts configuration classes, like extending the ActionMapping, makes the framework
extremely extensible and flexible to meet just about any application need. For example, If you wanted to
pass an additional parameter called ssl-required that controlled whether HTTP or HTTPS was used. In
EPricer we have created EPricerForward31ActionMapping which modifies the request metadata through
initialisation parameter.
- Extending the ActionServlet, if you need to modify the way in which the framework initializes itself,
this would be a place to change it. Like, if you want to implement filters, which will be processed during the
initialisation process, we can extend the ActionServlet class. As EPricerActionServlet in EPricer used for
applying some filers to the request.
- Extending the RequestProcessor, If you need to customize the manner in which your Struts
application processes a request, you can create your own customised request processor, and use it to
process all of the requests for the application. Since each sub-application can have its own Struts
configuration file, you can specify a different RequestProcessor for each sub-application. Like
EPricerRequestProcessor in EPricer.
- Extending the Action class, One of the reasons for doing this is that in many applications, there is
common logic that must be implemented by most of the Action classes. By letting this super Action class
contain most of this code, the redundancy can be eliminated. Like there is a class called EPricer31Action in
EPricer, which holds some common functionality, and down the line have been used by other classes.
struts-config.xml
The Struts configuration file makes it possible for you to declaratively configure many of your application’s settings. You can think of
the Struts configuration file as the rules for the web application.
The instance of this file, is specified in the web application deployment descriptor (web.xml). It is sole provider of the configuration
information for the Struts application. The following block entry has to be made in the deployment descriptor for struts-config.xml.
<web-app>
<servlet>
<servlet-name>NAME</servlet-name>
<servlet-class>DETAILED PATH OF CONTROLLER SERVLET</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SAME NAME AS IN SERVLET-NAME TAG</servlet-name>
<url-pattern>*.wss</url-pattern>
</servlet-mapping>
</web-app>
Form Beans
The form-beans element allows you to configure multiple ActionForm classes that are used by the views. Within the form-beans
section, you can configure zero or more form-bean child elements. Each form-bean element also has several child elements of itself.
struts-config.xml file showing the form-beans section
<struts-config>
<form-beans>
<form-bean name="shoppingCartForm"
type="com.oreilly.struts.order.ShoppingCartForm"/>
</form-beans>
</struts-config>
name A unique identifier for this bean, which is used to reference it throughout the framework. This value is required and
must be unique within a sub-application.
type The fully qualified name of a Java class that extends the Struts ActionForm/DynaActionForm class. This attribute is
required.
Global Forwards
The <global-forwards> section allows you to configure application level mappings of logical names to application relative URI paths.
The <global-forwards> section consists of zero or more <forward> elements as shown here.
The <forward> element maps a logical name to an application relative URI path.
<global-forwards>
<forward name="FPQAffectedCountriesDetail" path="/protect/fpCountriesDetailDisplay.wss" />
</global-forwards>
name A unique value that is used to reference this forward in the application. This attribute is required.
path An application relative or content relative URI to which control should be forwarded.This attribute is required.
struts-config.xml cont….
Global Exceptions
The global-exceptions section allows you to configure exception handlers declaratively at the application level. The global-exceptions
element can contain zero or more exception elements.
The <exception> element describes a mapping between a Java exception that may occur during processing of a request and an
instance of org.apache.struts.action.ExceptionHandler that is responsible for dealing with the thrown exception. The declaration of the
<exception> element illustrates that it also has several child elements.
<global-exceptions>
<exception
key="global.error.invalidlogin"
path="/security/signin.jsp"
scope="request"
type="com.oreilly.struts.framework.exceptions.InvalidLoginException"/>
</global-exceptions>
className The implementation class of the configuration bean that will hold the exception information. If specified, it must be a
descendant of org.apache.struts.config.ExceptionConfig, which is the default class when no value is specified.
handler The fully qualified Java class name of the exception handler that will process the exception. Default exception handling
class is org.apache.struts.action.ExceptionHandler.
key A message key that is specified in the resource bundle for this sub-application. This value is used by the ActionError
instance.
path The application-relative path of the resource to forward to if this exception occurs. This attribute is optional and the
framework will default to the input attribute for the action mapping if no value is specified here.
scope Identifier of the scope level, where the ActionError instance should be stored. The attribute value must either be
“request” or “session”. Default is “request”.
type The fully qualified Java class name of the exception that is to be handled. This attribute is required because it
identifies the exception, which can’t be assumed by the framework.
struts-config.xml cont….
Action Mappings
The <action-mappings> element configures the mappings from submitted request paths to the corresponding Action classes for a
particular sub-application. There is only one attribute of this tag, i.e., type, via which you can declare your own custom action
mapping, otherwise it will use the default action mapping provided by struts, i.e. org.apache.struts.action.ActionMapping.
<action path="/protect/customervalidate"
type="com.ibm.services.epricer.screen.customermanagment.CustomerInformationValidateAction"
input="CustomerInformationTile"
name="NewCustomer"
validate="true"
scope=”request”>
<forward name="managecomp" path="/protect/manageProducts.wss" />
<forward name="manageconfig" path="/protect/manageConfigurations.wss" />
</action>
name The name of the form bean. This value must be the name attribute from one of the form-bean elements defined
earlier. This attribute is optional and has no default value.
path The application-relative path of the submitted request, starting with a “/” character and without the filename
extension if extension mapping is used. This value is required.
scope This attribute is used to identify which scope level the form bean is placed. It can either be “request” or “session”. It
can only be specified if the name attribute is present. The default value is “session”.
type A fully qualified Java class name that extends org.apache.struts.action.Action class, is used to process the request.
validate A boolean value indicating whether the validate() method of the form bean, specified by the name attribute, should be
called prior to calling the execute() method of this action. This attribute is optional and will default to true.
Input The name of the resource, where the control will be redirect, if the validate gets failed.
struts-config.xml cont….
Message Resources
The <message-resources> element specifies characteristics of the message resource bundles that contain the localized messages for
an application. Each Struts configuration file can define one more message resource bundles. Each sub-application can define its own
bundles. The declaration of the <message-resources> element shows that it contains no child elements.
<message-resources parameter="ServicesEpricerScreens,ServicesEpricerCtm60msg"
factory="com.ibm.services.epricer.struts.EPricerMessageResourcesFactory">
</message-resources>
factory The fully qualified Java class name of the MessageResourcesFactory class that should be used. This attribute is
optional. The default value is org.apache.struts.util.PropertyMessageResourcesFactory.
parameter This attribute is the base name of the resource bundle. This attribute is required.
Plug-in
The plug-in element specifies a fully qualified class name of a general-purpose application plug-in module that receives notification of
application startup and shutdown events.. The class specified here must implement the org.apache.struts.action.PlugIn interface and
implement the init and destroy methods.
The declaration of the plug-in element shows that it may contain zero or more set-property elements, so that extra configuration
information may be passed to your class.
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config" value="/WEB-INF/tiles-config.xml" />
<set-property property="moduleAware" value="true" />
<set-property property="definitions-parser-validate" value="true" />
</plug-in>
What are Action Forms or Form Beans?
• The ActionForm class is used to capture input data from an HTML form and transfer it to the Action class.
• The ActionForm also acts as a “firewall” for your application in that it helps to keep suspect or invalid input out of your business tier
until it can be scrutinized by the validation rules.
• ActionForm class acts as a buffer to hold the state of what the user entered while it is being validated.
• ActionForm is also used to transfer data from the Action class back to the HTML form.
• ActionForms can have two different levels of scope, request & session. If request scope is used, an ActionForm will only be available
until the end of the request/response cycle. If you need to keep the form data around longer than the request, you can configure an
ActionForm to have session scope. This might be necessary if your application captures data across multiple pages.
Life Cycle of
ActionForm
Action and Action Related Classes
• The org.apache.struts.action.Action class is at the heart of the framework. Its purpose is to act as a
bridge between the client request and the business operation. The Action class is not the proper place to put
your application’s business logic. Action class is still part of the controller. It’s just been separated out from the
ActionServlet and RequestProcessor for the sake of convenience.
• Business logic belongs in the domain model. These may be EJBs, CORBA objects, or maybe just a layer of
services.
• Each Action class is typically designed to perform a single task or business operation on behalf of a client.
The business operations performed by the Action should be related and have a purpose of fulfilling one
functional requirement for the application.
• Whenever any Action class is invoked, it is the execute(), method of Action class, which gets executed every
time. So it’s the responsibility of the developer, to override this method properly.
• The execute() method of action class returns an object of ActionForward, which is actually responsible for
forwarding the control to the next view.
• The ActionForward class represents a logical abstraction of a web resource. This resource is typically a JSP
page or a Java Servlet.
• To return an ActionForward from an Action, the action mapping class is use to locate one that has been pre-
configured in the configuration file. The following code illustrates how you can use the action mapping to locate
an ActionForward based on its logical name.
and this logical mapping will have an entry in struts-config.xml like this..
<forward name="Success" path="/index.jsp" redirect="true"/>
The Presentation Tier
What exactly is a view- it represents a display of the domain model in a UI. There doesn’t have to be just a
single view of the model, there can actually be many different ways to represent the same model.
Although JSP is the main component used by struts application, there are additional components that can be
used by or in conjunction with JSP pages….
•HTML Documents, used to generate static content. They are unable to render any dynamic data, but they
are still valid to use whenever the view is static and you don’t need the dynamic capabilities of JSP.
•JSP Custom Tag Libraries, The JSP custom tags can play a very important role within a Struts application.
Although an application is not required to use them, in some particular scenarios, it would be very difficult
without them.
•JavaScript and Style Sheets, The Struts framework doesn’t prevent you from using JavaScript within an
application. On the contrary, it provides functionality within the tag libraries to help facilitate using JavaScript.
Style sheets are used to help web designers gain more control over the appearance of a web site.
•Multimedia Files, are used in just about every web application. These include but are not limited to:
-- Images (.gif, .jpg, etc.)
-- Audio (.wav, .mp3, etc.)
-- Video (.avi, .mpg, etc.)
Images are probably the most widely used, although for B2B applications, audio and video files are also
prevalent. The Struts framework supports using multimedia files within an application. The support is
achieved mainly through the use of custom tags, but you are also free to use standard HTML to render
these types of resources.
•Message Bundles, The message resources, or resource bundles are a very important component for Struts
applications. Not only do they provide a means to support localization, but they also help to reduce
maintenance time and redundancy throughout an application. Thus instead of hard-coding the string in every
page, you can specify it in the bundle and retrieve it using one of the custom tags.
The Presentation Tier cont…
•Java Beans, is used to access the data from the model. Data Transfer Object (DTO) aggregates various attributes from
one or more business entities and puts this information into a JavaBean instance. DTOs are effectively part of the model, since
they are just local, possibly immutable copies of the business objects. Within Struts applications, they are used by the view to
deliver the model data that is rendered along with the static information in the page.
•Action Forms, as already discussed, Action Forms are used to capture the data from HTML forms, and transfer it to Action
Class. Action forms act as a firewall to the application, because it scrutinized the data before sending to the class. Action Form
is also used to transfer the data from Action class back to HTML form, which provides more consistency.
•Struts Custom Tag Library, used to accomplish some of the tasks like defining controls in HTML forms, some iteration etc.
The Struts distribution includes four key tag libraries: bean, html, logic, and nesting.
Library Description
bean Tags useful in accessing JavaBeans and their properties, as well as
defining new beans.
html Tags used to create HTML input forms that can interact with the Struts
framework, and related to HTML tags.
logic Tags for managing the conditional generation of output, looping over
object collections for repetitive generation of output, and application
flow management.
nesting Tags that provide enhanced nesting capabilities to the other Struts tags.
Tiles
A framework for web page templates and layouts
M
e
It is common for a web page
Body
n to have the header, footer,
u
body and menu sections.
Footer
Tiles Components
Tile: Building blocks of your web page.
<taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>
/WEB-INF/tlds/struts-tiles.tld
</taglib-location>
</taglib>
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml"/>
<set-property property="moduleAware" value="true" />
<set-property property="definitions-parser-validate" value="true" />
</plug-in>
The Layout Page
<%@ taglib uri="/tags/struts-tiles" prefix="tiles" %>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr> <td colspan =“2"> <tiles:insert attribute= "header" /></td></tr>
<tr valign="top">
<td><tiles:insert attribute=“menu" /></td>
<td>
<!--BEGIN MAIN BODY CONTENT-->
<table width="95%" cellpadding="0" cellspacing="0" border="0">
<tr><td>
<tiles:insert name=“content" />
</td></tr>
</table>
<!-- END MAIN BODY CONTENT-->
</td>
</tr>
<tr> <td colspan =“2"> <tiles:insert attribute= “footer" /></td></tr>
</table>
tiles-def.xml – The Tiles Definitions
A Simple Definition:
<tiles-definitions>
<definition name="myDef" path="/pages/myLayout.jsp">
<put name="header" value="/pages/myHeader.jsp"/>
<put name="menu" value="/pages/myMenu.jsp"/>
<put name="content" value="/pages/myContent.jsp"/>
<put name="footer" value="/pages/myFooter.jsp"/>
</definition>
</tiles-definitions>
tiles-def.xml – The Tiles Definitions
Extending definitions:
<tiles-definitions>
<definition name="myLayout" path="/pages/myLayout.jsp">
<put name="header" value="/pages/myHeader.jsp"/>
<put name="menu" value="/pages/myMenu.jsp"/>
<put name="footer" value="/pages/myFooter.jsp"/>
</definition>
</tiles-definitions>
Forwarding to the Tile
<action path="/protect/logon"
type="com.ibm.services.epricer.screen.LogonAction"
input=“logonScreen"
name=“NewUser"
validate="true"
scope=”request”>
<forward name=“success" path=“homeScreen" />
</action>
Process Based Architecture
1. Front Servlet looks in servlet-config to get the process name which will handle
the request.
2. The Front Servlet then looks in process-config.xml to get the Process class, JSP
and XSL(s) and forwards request to the Process class.
3. The Process processes the request and gives the output to ProcessResponse
In the form of XML data.
4. Control is then forwarded to the JSP. JSP uses the XML data and XSL to produce
html output.
Struts Based Architecture
ActionServlet
Form Bean
Value object Action
Struts – A Model View Controller Architecture
VIEW CONTROLLER
EPricerActionServlet 3.Forwards the request EPricerRequestProcessor
JSP [Client] 1. Sends 2. Applies some filters to
4. Process the request
request. Responsible for
Components are – Request
packaging and routing HTTP for controller and
•Custom Tags traffic to the appropriate populates the form bean.
handler in the framework.
•HTML
•Java Resource Bundles 5. Sends for User 6. After validation, it
Input Validation. delegates the
•Struts Action Forms handling of Request to
•Value Objects EPricerForm Action class
•Tiles Common Ancestor for all
EPricer Forms.
[Responsible for Validating
the user input.] EPricerAction
13. Uses the Form Bean 11.Uses Value Object to set 7. Uses the Action Form, and
and value object for it executes the business
the attributes of Form Bean
representation. logic that is associated
12. Uses ActionMapping / EPricerForward31ActionMapping with the requested Action
through the Model.
to decide the next view
10.Model modifies the VO 8. Creates the Value Object
through business process(s) from request parameters &
& returns it back to Action. passes this VO to the model.
ote:
Though it is recommended in EPricer that Actions and Action Model
Forms should extend the EPricerForm and EPricerAction
espectively, but there are situations, where it has extended the 9. Performs the business operation
Action and ActionForm directly.
1. SB Services
2. DAB Services
3. Web Services
4. DAOs
Linking Struts and Process framework
CONTROLLER
EPricerActionServlet
3.Forwards the request EPricerRequestProcessor
1. Sends
Client Request
2. Applies some filters to
request. Responsible for
packaging and routing HTTP
4. Process the request
for controller.
traffic to the appropriate
handler in the framework.
5. It delegates the
handling of Request to
Action class
EPricerForward31Action