Struts
Struts
Agenda
• Introduction
• ”C” in MVC
• ”M” in MVC
• ”V” in MVC
• Workflow
• Configuring Struts configuration file
• Struts custom tags
• Validator framework
• File upload
• Pros and Cons
Introduction
Struts is a framework to develop MVC model 2
applications
Provides its own controller
Separates presentation logic and business logic
Open source
http://struts.apache.org/
Approximately 300 java classes divided into 8 top level
packages
Struts resides in the web tier
Struts applications are hosted by a web container
Makes heavy use of request and response objects
Named in the architectural sense meaning nearly invisible
pieces holding up buildings
Support different model implementations (Java bean,EJB
etc)
Supports different view implementations (JSP,XML/XSL)
Introduction
Struts packages
org.apache.struts.action
org.apache.struts.actions
org.apache.struts.config
org.apache.struts.taglib
org.apache.struts.upload
org.apache.struts.tiles
org.apache.struts.util
org.apache.struts.validator
Jar
struts.jar
“C” in MVC
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</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>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Config parameter should contain the path of the default struts config file.
“C” in MVC
Container will load the ActionServlet either when starting the server or
when the first request arrives for the servlet.
Init() method will be called before any request is processed by the
servlet.
Performs compulsory initializations like initializing the message bundle,
struts configuration data, data sources, plug-ins etc.
Users can extend the ActionServlet class.
One instance of this servlet class receives and processes all requests
Delegates the handling of the request to RequestProcessor object
RequestProcessor selects and invokes an Action class to perform the
requested business operation
Users can extend the RequestProcessor class.
“C” in MVC
Action class is the heart of the struts framework
Bridge between a client request and a business
operation
One action class for one business operation
Most important method is the execute method which
will be called by the controller when a request is
received from a client
Signature of the execute method:
http://localhost:8080/myapp/saveSubscription.do?method=update
will call the update method.
Struts ActionForm
Struts framework automatically collects input from
request, passes this data to an Action using a form
bean which can then be passed to the business layer.
An ActionForm is a JavaBean optionally
associated with one or more ActionMappings. Such a
bean will have had its properties initialized from the
corresponding request parameters before the
corresponding Action.execute method is called.
“V” in MVC
Sample ActionForm bean
public class UploadForm extends ActionForm
{
protected String myText;
protected FormFile myFile;
Sample
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
exception.outgoinglogcreate.action.error = Internal Server Error in Create
Outgoing Log
exception.outgoinglogupdate.action.error = Internal Server Error in Update
Outgoing Log
Configuring Struts Configuration File
Struts config file
Core of struts
Ties all the components of the struts application together
2 main parts are form bean and action mappings
Sections of struts-config.xml
Data source
Form bean (Form property)
Exception
Forward
Action
Controller
Message Resources
PlugIn
Each class in org.apache.struts.config package holds information from the specific section of the
configuration file
Classes in config package
ApplicationConfig
Holds configuration information that describes an entire struts application
DataSourceConfig
Holds information about data source.
Configuring Struts Configuration File
FormBeanConfig
To configure multiple DynaActionForm classes that are
used by the views
FormPropertyConfig
To configure form properties
<form-beans>
<form-bean name=“newOutgoingLog“
type="org.apache.struts.action.DynaActionForm">
<form-property name=“ccTo" type="java.lang.String" />
<form-property name=“subject" type="java.lang.Integer"
initial=”NewsLetter”/>
</form-bean>
<form-bean name=“newIncomingLog“
type="org.apache.struts.action.DynaActionForm">
<form-property name=“dueDate" type="java.lang.String" />
<form-property name=“assignee" type="java.lang.Integer"
initial=”NewsLetter”/>
</form-bean>
</form-beans>
Configuring Struts Configuration File
In execute method of Action class,
import org.apache.commons.beanutils.BeanUtils;
Global Exception
<global-exceptions>
<exception
key="exception.nullexception.error"
type=“java.lang.NullPointerException"
path="jsp/ECError.jsp"/>
</global-exceptions>
2 types
1.Global forward
2.Action specific forward
Global forward
<global-forwards>
<forward name="success" path="/jsp/Success.jsp"></forward>
</global-forwards>
In action class
ActionForward forward = null;
forward = mapping.findForward(“success”);
return forward;
Configuring Struts Configuration File
ActionConfig
Describes a mapping between a specific request URI and a corresponding Action class.
Attributes
path – URI path
name – Name of the form bean associated with this Action
type – Name of the java class that extends Action/DispatchAction class
scope – specifies the scope in which the form bean is placed (request or session)
parameter – Name of the request parameter which holds the name of the method to
be executed.
forward – Name of the servlet/JSP which will be forwarded to instead of calling the Action
class
include – Name of the servlet/JSP which will be included with the response instead of calling the Action
class (type, forward and include are mutually exclusive and exactly one should be specified
validate – Boolean value indicating if validate() method should be called before calling Action class method
Configuring Struts Configuration File
ControllerConfig
To declaratively assign the processor class
(RequestProcessor) and modify its functionality
Configuring Struts Configuration File
MessageResourcesConfig
Specifies message resource bundle that contains localized messages for an
application
<message-resources parameter="org.worldbank.encorr.resources.ApplicationResources”/>
Configuring Struts Configuration File
PlugInConfig
To discover resources dynamically at startup.
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
</plug-in>
Struts custom tags
Package
org.apache.struts.taglib
TLDs
struts-html.tld
struts-bean.tld
struts-logic.tld
struts-nested.tld
struts-template.tld
struts-tiles.tld
The "struts-html" tag library contains JSP custom tags useful in creating dynamic
HTML user interfaces, including input forms.
In JSP,
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:javascript>
Struts custom tags
<html:javascript>
Custom tag that generates JavaScript for client side validation based on the
validation rules loaded by the ValidatorPlugIn
<html:javascript formName="newOutgoingLog"/>
<html:form>
Custom tag that represents an input form, associated with a bean whose
properties correspond to the various fields of the form.
<html:form action="outgoing.do" method="post" onsubmit="return
onClickSave(this);">
<html:hidden>
Custom tag for input fields of type "hidden".
<html:hidden property="ticketStatus" value="C"/>
<html:select>
Custom tag that represents an HTML select element, associated with a bean
property specified by our attributes
<html:options>
Tag for creating multiple <select> options from a collection.
Struts custom tags
public class ListData
{
public String optLabel = null;
public String optValue = null;
ld = new ListData();
ld.setOptValue(“101”);
ld.setOptLabel(“Tamil”);
al.add(ld);
ld = new ListData();
ld.setOptValue(“102”);
ld.setOptLabel(“Hindi”);
al.add(ld);
request.setAttribute("languageList",al);
<html:select property="language">
<html:options collection="languageList" property=“optValue"
Struts custom tags
<html:errors>
Custom tag that renders error messages if an appropriate request attribute has
been created.
<html:errors/>
<html:file>
Custom tag for input fields of type "file".
Validator framework
Purpose
For performing data validations on form data.
If any validation fails the application redisplays the HTML form so that the invalid data can
be corrected
Pluggable system of validation routines that can be applied to form beans.
1.validator-rules.xml
Declares the validation routines with a logical name for each routine.
2.validation.xml
Defines which validation routine should be applied to which form bean
property.
It uses logical names of form beans from the struts-config.xml file along
with the logical names of validation routines from validator-rules.xml
Validator framework
Struts-config.xml
<form-bean name="newOutgoingLog"
type="org.apache.struts.action.DynaActionForm">
<form-property name="subject" type="java.lang.String"></form-property>
</form-bean>
Validator-rules.xml
<validator name="required"
classname="org.apache.struts.validator.FieldChecks"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
msg="errors.required">
<javascript><![CDATA[
function validateRequired(form) {
……………………………………………………….
}]]>
</javascript>
</validator>
Validator framework
Validation.xml
<form name="newOutgoingLog">
<field property="subject" depends="required">
<arg0 key=“Subject field" resource="false"/>
</field>
</form>
In resource bundle,
In struts-config.xml,
In OutgoingLogBean,
Open source
Reduces the development time
No hard codings as struts values are represented in XML or properties file
HTML custom tags (Minimize Java code in JSP)
Form field validation
Cons