Overview of Struct
Overview of Struct
Ken Sipe
Chief Instructor / TO
Code Mentor
Presentation Goal
Provide enough understanding for
someone new to start leveraging Struts.
Dig deep with several nuggets tips for
attendees well versed in Struts.
Presentation Agenda
Struts Intro
Struts Fundamentals
Struts Tags / Working with Forms
Struts Validation
Tiles
About the Speaker
Sun Certified Java 2 Architect.
Instructor for VisiBroker for Java, OOAD,
Rational Rose, and Java Development.
Frequently speaks on the subject of
distributed computing programming,
including CORBA and EJB architecture.
JBoss Certified Developer ;)
Understanding the JSP
Models
With a Quick Look at Java Web Apps
Java 2 Web Applications
Java 2 web application options:
– Servlets
• + Great for Java people
• - Difficult to manage graphical changes in HTML
layout.
– JSP
• + Great for web developers
• - Seductive tendency to write logic in the JSP
page.
JSP Model 1
Web applications where JSP pages are used
for every aspect of the development.
Option 1 Option 2
JSP Model 1 Observation
JSP1 JSP3 The Good
– Easiest Solution
JSP2 JSP4 The Bad
– Presentation and Logic
Presentation Logic are mixed.
Ctrl Presentation The Ugly
Presentation Logic – No reuse possibilities
Ctrl Present.
Present. Logic
JSP Model 2
Web applications where JSP pages are used
for the GUI aspect of the web development
and the logic of the application is placed in
the servlets it posts to.
Model 2
Logic Control The Good
– Reuse opportunities
• Other application may be able to
use the same code.
JSP1 JSP3 The Bad
– There is no longer a one to
JSP2 one mapping from a view to a
single source of code.
The Ugly
– Takes more forethought.
Introduction MVC
What Is a MVC?
MVC stands for model / view / controller.
– A software pattern where logic is separated
from the model and view in order to provide
for better reuse possibilities.
– A software pattern recognized in the early
days of small talk.
– Documented in the GoF book.
Web Application MVC
Controller
Pattern
1
(Servlet) Model
2 – Information is provided in
objects or beans
Model
View
(Beans)
3 – The JSP provide the view
View 4 Controller
View – Servlet provides control logic
5 View
(JSPs)
View
(JSPs) and becomes the controller
View
(JSPs)
(JSPs)
(JSP)
MVC Collaboration Diagram
Controller
1: Post 2: Retrieve Data
Browser Servlet Data
Res ource
3: Establish
bean state,
then place in
4: redirect to session or
appropriate view request
object
5: Access beans
JSP Beans
2: Get Mapped
Action
Diagram 3: Invoke mapped
Act ion Bean Controller
1: Pos t 4: Retrieve Data
Browser ActionServlet ActionBean Data
Resource
Front
Controller
5: Establish
bean state,
7: redirect to
t hen place in
appropriate view 6: Establish Form
session or
State
request
object
8: Get View
The View Information The Model
<web-app>
<servlet> ActionServlet
<servlet-name>action</servlet-name>
<servlet-class>
ActionServlet is provided by
org.apache.struts.action.ActionServlet the framework.
</servlet-class>
<init-param> The Servlet must be mapped
<param-name>debug</param-name> in the web.xml file.
<param-value>2</param-value>
</init-param> – Must have
<init-param> configuration file
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml mapped
</param-value>
Lastly, Map the *.do URI to
…
</servlet> the Action Servlet
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<struts-config> strut-config.xml
<!-- ========== Data Source Configuration === -->
<!-- ========== Form Bean Definitions === -->
<form-beans> XML configuration file
<form-bean name="LogonForm"
type="com.codementor.LogonForm"/> Allows for:
</form-beans>
<!-- ========== Global Forward Definitions === --> – DataSource definition
<global-forwards> </global-forwards>
– Logical name
<!-- ========== Action Mapping Definitions === -->
<action-mappings>
definitions for Forms
<action path="/logon"
type="com.codementor.LogonAction"
– View mappings
name="LogonForm" • Local
scope="request"
input="/logon.jsp"> • Global
<forward name="success" path="/sucess.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>
</action-mappings>
</struts-config>
Strut-config.xml
<action path="/logon“ For requests that hit URL=“/logon”
type=“com.codementor.LogonAction” The frame work will invoke execute() on
an instance of class
com.codementor.LogonAction
name="LogonForm"
Store request parameters in form variable
“LogonForm” which is defined in another
location in the xml document.
<forward name="failure"
path="/failure.jsp" /> If the logical name returned by perform() is
“failure” go to page “/failure.jsp”
<forward name="success"
path="/success.jsp" /> If the Logical name returned by perform()
is “success” go to “/success.jsp”
</action>
Action Bean
import org.apache.struts.action.*;
if(theForm.getUserName().equals("borcon"))
{
forward="success";
}
return mapping.findForward(forward);
}
}
Action Form
import org.apache.struts.action.ActionForm;
Action Form has properties
public class LogonForm extends ActionForm { which map to the HTML
private String userName;
private String password; page.
Additionally the form can:
public String getUserName() {
return userName; – Reset
}
public void setUserName(String userName) { – Validate
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
}
Strut
<html:html locale="true">
Powered JSP
<head>
<title>Logon Form</title>
<html:base/>
</head>
<body bgcolor="white">
<html:errors/>
<html:form action="logon" focus="userName">
User Name: <html:text property="userName" size="16"
maxlength="16"/>
password: <html:password property="password" size="16"
maxlength="16"
<html:submit property="submit" value="Submit"/>
<html:reset/>
</html:form>
</body>
</html:html>
Creating Your First Struts
Application
Struts Installation
Downlad the zip
– http://apache.mirrors.hoobly.com/jakarta/strut
s/binaries/jakarta-struts-1.1.zip
– Unzip and go!
– There isn’t an “install”, however there are
several files you’ll need.
– Readme.txt has details
Main Files of interest
– *.jar , especially struts.jar
– *.tld
– struts-blank.war
Steps to Building
Step 1: Build your JSP in HTML format
– It’s back to editing code
Step 2: Convert to Struts format
Step 3: Write the matching ActionForm
– public class LogonForm extends
ActionForm {}
Step 4: Write the Action class
– public class LogonAction extends
Action {}
Steps to Building
Step 5: Register the entries in struts-config.xml
<action path="/logon"
type="com.codementor.struts.LogonAction"
name="logonForm"
input="/Logon.jsp" >
<forward name="success" path="/Success.jsp" />
<forward name="failure" path="/Failure.jsp" />
</action>
Step 6: Configure web.xml with the ActionServlet
JSP Pages
Three Pages
– Login Page
– Success Page
– Failure Page
Logon Page – HTML Version
<html>
<head>
<title>Login Form</title>
</head>
<body bgcolor="#ffffff">
<form action="logon.do">
User Name: <input type="text"
name="userName" size="16"
maxlength="16"/><br />
Password: <input type="text"
name="password" size="16"
maxlength="16"/><br />
<input type="submit" name="Submit"
value="Submit">
Logon Page – Struts
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html>
<head>
<title>Login Form</title>
</head> Added a cool feature
<body bgcolor="#ffffff">
<html:form action="logon.do" focus="userName">
<br>
User Name: <html:text maxlength="16"
property="userName" size="16"/><br />
Password: <html:text maxlength="16"
property="password" size="16"/><br />
<html:submit value="Submit" property="Submit"/>
Success and Failure Pages
Success.jsp Failure.jsp
<html> <html>
<head> <head>
<title> <title>
Success Failure
</title> </title>
</head> </head>
<body bgcolor="#ffffff"> <body bgcolor="#ffffff">
<h1> <h1>
Successful Login Failed Login
</h1> </h1>
</body> </body>
</html> </html>
Create Form Bean Class
package com.codementor;
import org.apache.struts.action.ActionForm;
type="com.codementor.LogonForm" />
</form-beans>
…
</struts-config>
package com.codementor;
import org.apache.struts.action.*; Action Class
import javax.servlet.http.*;
if(logonForm.getUserName().equals("mentor"))
{
forward = "success";
}
return mapping.findForward(forward);
}
}
Action Class Config
…
<action-mappings>
<action path="/logon"
type="com.codementor.LogonAction"
name="logonForm"
input="/Login.jsp"
scope="request" />
</action-mappings>
</struts-config>
… Map The Forwards
<action-mappings>
<action path="/logon"
type="com.codementor.LogonAction"
name="logonForm"
input="/Login.jsp"
scope="request" >
<forward name="success" path="/Success.jsp"
/>
<forward name="failure" path="/Failure.jsp" />
</action>
</action-mappings>
</struts-config>
<web-app>
<servlet> Struts in web.xml
<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> Sets the logging level for struts
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
Loads ActionServlet on startup
** important if there is a JSP page
which could be referenced from the
Client **
Web.xml URI Mapping
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Configure Tags
…
<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>
</web-app>
/sample
Configure WebApp
Logon.jsp
Success.jsp
Failure.jsp
/WEB-INF
web.xml
struts-config.xml
*.tld – all the struts tld files
/lib
*.jars - all the struts jars
/classes
LogonAction
LogonForm
Run The WebApp
Demo
Summary
JSP / Servlet Models
MVC
Struts Basics
Creating a Struts Application
Questions?
Struts Fundamentals
Section Agenda
Form Beans
Action Classes
Struts Configuration File
Form Beans
Form Bean Types
ActionForm
– Sub-class to create a standard form
ValidatorActionForm
– Sub-class in order to use the validator
framework
DynaActionForm
– Generic Form
– Form is defined in xml
DynaValidatorActionForm
– DynaAction form which can be used with the
validator framework
ActionForm Class
Basic Type
Follows Rules for JavaBean
– Collection of properties
Methods
– Reset()
– Validate()
public class LogonForm extends ActionForm {}
FormBean Reset() Method
public void reset(ActionMapping mapping,
HttpServletRequest request) { }
Example LogonForm
<struts-config>
<form-beans>
<form-bean name="LoginForm"
type="org.apache.struts.action.DynaActionForm
">
<form-property name="userName"
type="java.lang.String" />
<form-property name="password"
type="java.lang.String" />
</form-bean> </form-beans>
Working with DyanForms
Handling DynaForms in an Action Class is a little
different.
– There are no strongly type properties.
– Consider a HashMap where the configured
name is the key
Example:
DynaActionForm form =
(DynaActionForm)actionForm;
form.get("userName");
DynaValidatorActionForm
Work the same as DynaActionForms
Provide ability to use the validator
framework.
Actions
Action Types
Actions
DispatchActions
LookupDispatchActions
ForwordActions
TilesActions
Action Characteristics
Typically have one method, the execute method.
– Models after the command pattern
Dissimilar from a Servlet
– Lacks the doGet / doPost characteristics
– Requires a different design as compared to
Servlets
• May require an Action for setting up display and an
Action for retrieving POSTs
• May programmatically determine the action in the
Action class
• May use one of the DispatchActions
Action Class
Super-class to all Actions
public class LogonAction extends Action {
localhost:8080/sample/logon.do?action
=login
LookupDispatchAction
LookupDispatchAction provides a configurable way
to define logical name mappings to physical
method names, which are not exposed to the
public.
– Requires no extra configuration in the struts-
config
– Short-Hand XML
<action path="/home" forward="index.jsp"/>
TilesAction
Used to provide controller logical to tiles.
– Explained in the Tiles Section of the course.
Has a slightly different execute signature
public ActionForward execute(ComponentContext
context,
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse
response)
throws Exception {
Forwards
Local Forwards
Refers to the forwards defined per action
<action-mappings>
<action input="/Login.jsp" name="logonForm" path="/logon"
scope="request" type="com.codementor.LogonAction" >
<forward name="success" path="/Success.jsp" />
<forward name="failure" path="/Failure.jsp" />
</action>
</action-mappings>
Name is a logical String
Path is a view element is
– Relative Resource (such as Success.jsp)
– Tiles definition
– Can be any URL
Global Forwards
Global Forwards are forwards which are declared
in the global section of the struts-config file.
Reduces multiply declared local forwards
Great to use with the <html:link> tag (discussed
later)
<struts-config>
…
<global-forwards>
<forward name="Home" path="/viewHome.do"
/>
<forward name="Logon" path="/Logon.jsp" />
</global-forwards>
Forward to Actions
It is common to have a forward go to another
action class.
<forward name="failure" path="/failure.do" />
Forward Redirects
By default forwards are forwards and not
redirects.
To redirect the client
<forward name="success"
path="/Success.jsp" redirect="true“ />
Struts Configuration File
Struts Configuration File
Defines the configuration for the Struts
Application Module
Configured in the web.xml file for the
ActionServlet
By convention usually named struts-
config.xml
This section will walk through all the XML
elements in the struts configuration file.
Struts-Config.xml
DataSources
FormBeans
Global Exceptions
Actions
Controller
Message Resources
PlugIns
Data Sources
Don’t use it, but here’s how
<data-sources>
<data-source>
<set-property property="driverClass“
value="org.postgresql.Driver"/>
<set-property property="password“
value="mypassword"/>
<set-property property="url“
value="jdbc:postgresql://host/mydatabase"/>
<set-property property="user“
value="myusername"/>
</data-source>
</data-sources>
Form Beans
Location where are form beans are defined.
Provides a logical name mapped to either:
– Physical ActionForm Class
– DynaActionForm Class
DynaActionForms define there form beans
structures.
<form-beans>
<form-bean name="logonForm"
type="com.codementor.LogonForm" />
</form-beans>
Global Exceptions
Struts defines a way to do declarative exception
handling
– Exceptions are mapped to forward paths
– Can be in combination with exception keys.
Global exceptions are leverage if there isn’t a
configured local exception handler.
<global-exceptions>
<exception
type="app.ExpiredPasswordException"
path="/changePassword.jsp"/>
</global-exceptions>
Global Forwards
Location of forwards defined to be global.
Provides default forward.
<global-forwards>
<forward name="Home"
path="/viewHome.do" />
<forward name="Logon"
path="/Logon.jsp" />
</global-forwards>
Action Mappings
Action mappings is where the actions are
configured.
Maps the action to the form bean.
Provides local forwards.
<controller
processorClass="org.apache.struts.tiles.
TilesRequestProcessor" />
RequestProcessor
Provides access to preprocessing to all requests
– No need to extend the ActionServlet
Provides hooks into
– ActionCreate
– ActionForm
– ActionForward
– Processing:
• Exceptions
• Forwards
• Locale
• Path
• Populate
Message Resources
Location to Configure application
resources.
Used for Internationalization
<message-resources
parameter="com.codementor.Application
Resources" />
Plugins
Used to configure Plugins for the application
Plugins provide startup and shutdown functionality
through
– Init()
– Destroy
Commonly used for Tiles and Validation Framework
<plug-in
className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml" />
</plug-in>
Summary
Form Beans
Action Classes
Struts Configuration File
Questions?
Working Struts Tags
Section Agenda
Common Tags
Working with Forms
Useful Struts Java Classes
Common Tags
Most Common Struts Tags
html:form bean:write
html:img bean:define
html:image logic:iterator
html:errors logic:match
html:link logic:equal
html:multibox logic:notEqual
html:radio Nested versions of all these
html:checkbox tags
html:text tiles:insert
html:select tiles:put
html:options
Common Non-Form Tags
Define
Links
Images
Write
Message
Iterator
Nested Tags
Bean:Define
Use for:
– Access to bean not in the scope of an html
form
– To provide clarity when working with multiple
nested properties
– To provide script variable for included JSP
pages.
Does NOT create an instance of a bean
– It provides access to a bean in scope
Don’t use to define a form bean to a new script
variable name
Bean:Define
<bean:define id=“employeeList“
name=“selectEmployeesForm“
property=“employeeList“
type="java.util.Collection"/>
Image Link
<html:link page="/viewReport.do">
<html:img src="/images/emp_button_view_report.gif"
/>
</html:link>
Parameterized Links
Links which depend on information available
through the form bean
<html:link page="/viewReport.do"
paramId="model“
paramName="viewModelForm"
paramProperty="model">
<html:img
src="/images/emp_button_view_report.gif" />
</html:link>
Parameterized Link
Will create a link on the image to:
/viewReport.do?model=<%=viewModelF
orm.getModel() %>
Which may look like:
/viewReport.do?model=detail
Images
There are 2 images tags
– html:img
• Used for normal images
• Used with links
– html:image
• Used for images which function as submit
buttons
• Must be in an struts form
<html:img>
<html:link page="/viewReport.do">
<html:img
src="/images/emp_button_view_report.gif" />
</html:link>
Or Simply
<html:img
src="/images/emp_button_view_report.gif" />
<html:image>
<html:form action=“/action.do”>
<html:link
src="/images/emp_button_view_report.gif
" />
</html:form>
Bean:write
Used to retrieve a property from:
– a form bean
– a defined scripted variable (by
bean:define)
<bean:write name=“modelForm”
property=“clientName”/>
Bean:Write
If the named object is an object
you do not have to define a property
Ex: <bean:write name=“id” />
JSP Equivalent:
<%= modelForm.getClientName() %>
Displaying HTML on HTML
Struts will not display the source of html of
an html page by default
Use the bean:write with the filter set to
false.
Bean:message
Used to retrieve a property from a
configured property file.
We’ll look at this in detail in the
Internationalization section.
<bean:write name=“modelForm”
property=“clientInfo”/>
Logic:iterate
Used to iterate
– An array
– A Collection
All tags between the <logic:iterate> open
and close tag will execute for each
element.
Logic:iterate Example
This would go through all the employees of the
employeesForm
The employeesForm is the string from the struts
config for the form bean that is assigned to the
action that forwarded to this JSP.
In a few slides we’ll evolve this example to
something useful.
<logic:iterate id=“employeesForm"
property=“employees">
</logic:iterate>
Nested Tags
Most of the tags have a nested version.
– Usually reducing the required
attributes for the extended tag.
Use Often!!!
Great for working through an iterator
Great for removing form bean
dependencies in the JSP page.
Nested Tags Example
Without nested in a form
<bean:write name=“modelSummaryForm”
property=“clientName”/>
With nested
<nested:write property=“clientName”/>
<html:select property=“employee”>
Used to create an html select in order to
create a combo box
Combo Box
This tag performs the following:
– On JSP forward
• Gets the value of the form beans getEmployee()
method
• Creates an html select tag
• Defaults the value of the select tag to the value
retrieved.
• If there isn’t an option that matches the select
choice then it’s up to the browser to decide
– On Submit
• Gets the option selected
• Sets the value of the like named property in the
form bean
HTML Selects
Observations for the example below
– The name of the select is employees
– The default value is Ken, Ken will be
displayed in the drop down
– The list will have Ken, Tammy and Amanda
– The value of Tammy is 102
– The value of Amanda is Amanda
<select name="employees">
<option value="101"
selected="selected">Ken</option>
<option value=“102”>Tammy</option>
<option >Amanda</option>
</select>
Options for the Drop Down
Hard-Coded String
– Struts
– Html
Array of Strings
Collections
•You can hard code the value of the dropdown as well. For example:
<html:select property=“employee” value=“Ken”>
<html:select property=“employee”>
<html:options value=“Ken” />
<html:options value=“Amanda” />
<html:options value=“Amelia” />
</html:select>
String Array Options
In this example, there is an employeeList
property in the form bean which returns a
String array.
Each elements of the array will be a name
and value of an option.
<html:select property=“employee”>
<html:options name=“employeeList” />
</html:select>
Collections Options
When working with a collection of Java objects
which are not Strings
Collection: Identifies the collection property name
of the form bean
Property: is a property on the object in the
collection
– Used for the value of the option.
– In this case the objects in the collection have
a property getEmployeeID()
labelProperty: is a property on the object in the
collection
– Used for the label of the option
– In this case the object is getName()
Collections Options
Example:
<html:select property=“employee”>
<html:options collection=“employeeList”
property=“employeeID”
labelProperty=“name” />
</html:select>
public class Employee {
private String name;
Employee Class
private String employeeID;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmployeeID() {
return employeeID;
}
public void setEmployeeID(String employeeID)
{
this.employeeID = employeeID; } }
Collections Output
<html:select property=“employee”>
<html:options collection=“employeeList”
property=“employeeID” labelProperty=“name”
/>
</html:select>
Results in:
<select name="employee">
<option value="101" >Ken</option>
<option value=“102”>Tammy</option>
<option value=“102”>Amanda</option>
</select> Where employeeID for the Ken object is
101 and Ken is the name
Radio Button
<html:radio property=“status” value=“Full Time” />
<html:radio property=“status” value=“Part Time” />
Used to create an html set of input type radio
buttons
This tag performs the following:
– On JSP forward
• Gets the value of the form beans getStatus()
method
• Creates an html input tag of type radio
• Defaults the value to the radio of the same value
– On Submit
• Gets the value of the radio
• Sets the value of the like named property in the
form bean
pe=“radio” name=“status” value=“Full Time” >Full Time</input>
pe=“radio” name=“status” value=“Part Time” > Part Time</input>
Check Box
<html:checkbox property=“isUSCitizen”
value=“wasUSCitizen” />
Used to create an html input check boxes
Properties must be of type booleans
Check Box
This tag performs the following:
– On JSP forward
• Gets the value of the form beans wasUSCitizen()
method
• Creates an html input tag of type checkbox, named
isUSCitizen
• Defaults the value to the checkbox to the value of
wasUSCitizen()
– On Submit
• Gets the value of the checkbox
• Sets the value of the isUSCitizen property in the
form bean
Produces a /employee.do?action=add
For the add submit button
JavaScript Action Switch
Example:
<html:image
src=“images/emp_button_run_model.gif”
onclick=“document.forms[0].action=‘runMod
el.do” border=“0” />
Struts Classes
Struts Classes
ImageButtonBean
LabelValueBean
RequestUtil
Jakarta Commons
– BeanUtil
ImageButtonBean
Provides the X and Y coordinates of where
on an image the mouse was clicked.
Properties:
–X
–Y
– isSelected
A Property of this type in the form bean can
provide this information
LabelValueBean
Utility Class to provide a different display
name from the selection name.
How do we produce the following html:
<select name=“listType”>
<option value=“ST”>Standard
<option value=“SL”>Select
</select>
LabelValueBean Ex
JSP Code
<html:select property=“type”>
<html:options collection=“listTypes”
property=“value” labelProperty=“label” />
</html:select>
Java Code
Form.addListTypes(new
LabelValueBean(“Standard”,”ST”));
Form.addListTypes(new
LabelValueBean(“Select”,”SL”));
RequestUtil
Utility for working with the request object.
Provides:
– actionURL
– absoluteURL
– createActionForm
– URL encoding
– Access to ActionErrors
– Access to Action Mappings
– Printable URL
BeanUtil
Was part of Struts 1.0
Now part of Jakarta Commons
– Which is included with Struts 1.1
Great Utility to copy values of the
properties of one bean to the values of
the properties of the same name of
another bean.
Summary
Common Tags
Working with Forms
– Most data input tags were discussed.
Useful Struts Java Classes
Questions?
Struts Validation
Section Agenda
Simple Bean Validation
Understanding Validation Framework
Business Level Validation
Validation Opportunities
Client-Side
– javascript
Server-Side
– Form Bean
– Action Class
– Validator Framework
Client Side Validation
In addition to your own javascript, Struts provides
the ability to generate javascript based on
configuration.
– Discussed further in validator framework
Javascripts Pros:
– Convenience to the client
– Provides a network throttle
Javascript cons:
– Multi-Browser support
Server-Side Validation
Server-Side Validation
Common Validation Classes and
Configuration
Form Bean Validation
Action Bean Validation
Validation Framework
Classes
ActionErrors
– Used in struts to contain all the errors
from a validation point
ActionError
– A specific validation error, which will
be put in the ActionErrors
– Contains an error key (which may be
used with the resourse bundle)
Resource Messages
Application.properties file configured with the
message-resources tag in the struts-config.xml
ApplicationResources.properties file:
error.username.required=Username is require
error.password.required=Password is required
A Look at MessageFormat
It’s required for the validation framework to under
the java.text.MessageFormat class.
Provides a way to have parameterized message
– Single digit values from 0-9 are used as
place holders in a String text.
• {0},{1},{2},…
– These provides the ability to have a generic
message where specifics can be inserted in
the message at a latter time.
Message Format Ex.
Example Message:
String message = "The disk named {0}
contains {1} files.";
String[] args = {"Foo","300"};
System.out.println(MessageFormat.forma
t(message,args));
Output:
The disk named Foo contains 300 files.
Server-Side Validation
Common Validation Classes and
Configuration
Form Bean Validation
Action Bean Validation
Form Bean Validation
In order to validate a form bean the following
conditions must exist:
– The validate method of the form bean must
be implemented.
– The form bean must be configured in the
configuration file to use validation
• This is configured by action class.
The validation occurs prior to the action class
being invoked.
– If there is an error the client is redirected to
the configured input page.
Validate() Method
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ( (userName == null) || (userName.length() < 1)) {
errors.add("userName", new
ActionError("error.username.required"));
}
return errors;
ApplicationResources.properties file:
} error.username.required=Username is requ
error.password.required=Password is requir
Validate Method
Return ActionErrors.size() == 0 or return
null if there are no errors
Add Errors to the ActionErrors for each
error
The keys map to the properties in the
configured property file.
Bean Validation Config
<action input="/Login.jsp" name="logonForm"
path="/logon" scope="request"
type="com.codementor.LogonAction" validate="true“ >
<forward name="success" path="/Success.jsp"
redirect="true" />
<forward name="failure" path="/Failure.jsp" />
</action>
saveErrors(request,errors);
return mapping.findForward(forward);
// the forward would need to be set
}
Validation Framework
Validation Framework
Configured in XML
Rules defined in XML
Pre-defined validators
User-defined validators
Can be configured to provide javascript to
the client
Must use the ValidatorForm
Works with Resource Bundle
XML Configuration
Although there can be any number of files used for
validation configuration, there are typically 2:
– Validation-rules.xml
• Contains the xml defined rules
• Typically generic / Non application specific
• Provided with the struts download
– Validation.xml
• Configuration of the rules from the first xml file, to
the forms and fields defined in the struts-config file.
• Typically application specific.
Validation-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[ …
Configure Validation
Example
Create the Validation.xml
Configure the struts application to use the
validation framework
Create or Copy the applications.properties
file
Configure the application.properties file in
the struts configuration file
Configure the output location to show the
error
Validation.xml Username Ex
<form-validation >
<formset>
<form name="logonForm" >
<field
property="userName"
depends="required" />
</form> ApplicationResources.properties file:
<plug-in
className="org.apache.struts.validator.Validat
orPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-
INF/validation.xml" />
</plug-in>
Application.properties File
#Struts Validator Basic Error Message
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.
errors.invalid={0} is invalid.
errors.byte={0} must be an byte.
errors.short={0} must be an short.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.float={0} must be an float.
Property File Configuration
Configure the property file in the struts-
config.xml file
This example assumes that it is the WEB-
INF/classes/com/codementor directory of
the web application.
<message-resources
parameter="com.codementor.Application
" />
Displaying Strut Errors
<html:errors/>
– Errors are displayed where this tag is
placed in the JSP file.
<html:errors property=“userName”/>
– Placing errors close to the property of
choice
– Displays only the errors for this
property
Pre-Defined Validators
Pre-Defined Validators
Required
minLength
maxLength
Range
Date
Basic types (integer, long, double, float )
Email
– Validates that the email could be valid
creditCard
– Validates that the number could be valid
Mask
– Used to check regular expression
Default Property Keys
#Struts Validator Basic Error Message
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.
errors.invalid={0} is invalid.
errors.byte={0} must be an byte.
errors.short={0} must be an short.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.float={0} must be an float.
errors.double={0} must be an double.
Default Property Keys
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is not a valid credit card
number.
errors.email={0} is an invalid e-mail address.
MinLength Configuration
<field property=“userName“
depends="minlength">
<arg0 key=“userName“ resource=“false”/>
<arg1 name="minlength"
key="${var:minlength}"
resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
</field>
ApplicationResources.properties file:
errors.minlength={0} can not be less than {1} characters.
MaxLength Configuration
<field property=“userName“
depends="maxlength">
<arg0 key=“userName“ resource=“false”/>
<arg1 name="maxlength"
key="${var:maxlength}"
resource="false"/>
<var>
<var-name>maxlength</var-name>
<var-value>5</var-value>
</var>
</field>
ApplicationResources.properties file:
errors.maxlength={0} can not be greater than {1} characters.
Range Configuration
<field property=“priorty“ depends=“range">
<arg0
key=“responseForm.priority.displayname“ />
<arg1 name=“range" key=“${var:min}”
resource="false"/>
<arg2 name=“range" key=“${var:max}”
resource="false"/>
<var>
<var-name>min</var-name>
<var-value>1</var-value>
</var>
<var>
<var-name>max</var-name>
ApplicationResources.properties file:
<var-value>4</var-value>
errors.range={0} is not in the range {1} through {2}.
</var>
Date Configuration
<field property=“date“ depends=“date">
<arg0 key=“responseForm.date.displayname“
/>
<var>
<var-name>datePattern</var-name>
<var-value>MM/dd/yyyy</var-value>
</var>
</field>
ApplicationResources.properties file:
errors.date={0} is not a date.
Double Configuration
<field property=“amount“
depends=“double">
<arg0
key=“responseForm.amount.displaynam
e“ />
</field>
ApplicationResources.properties file:
errors.double={0} must be an double.
CreditCard Configuration
<field property=“creditCard“
depends=“creditCard">
<arg0
key=“responseForm.creditCard.displayname
“ />
</field>
ApplicationResources.properties file:
errors.creditcard={0} is not a valid credit card number.
Mask Configuration
<field property=“postalCode“
depends=“mask">
<arg0
key=“responseForm.postal.displayname“ />
<var>
<var-name>mask</var-name>
<var-value>^\d{5}\*$</var-value>
</var>
</field> ApplicationResources.properties file:
errors.invalid={0} is invalid.
Common Masks
Phone
– ^\(?(\d{3})\)?[-| ]?
(\d{3})[-| ]?(\d{4})$
Zip
– ^\d{5}\d*$
– ^\d{5}(-\d{4})?$
Additional Validation
Configuration Options
Using Global Constants
It is possible to define global constants in the
validation configuration file.
<form-validation>
<global>
<constant>
<constant-name>zip</constant-name>
<constant-
value>^\d{5}\d*$</constant-value>
</constant>
</global> <var>
<var-name>mask</var-name>
<var-value>${zip}</var-value>
</var>
Configure Multiple Rules
<form-validation >
<formset>
<form name="logonForm" >
<field property="userName“
depends="required,mask" >
<arg0 key=“logon.username.displayname” />
<var>
<var-name>mask</var-name>
<var-value> ^[a-zA-Z0-9]*$</var-value>
</var>
…
Configure a Message
<form-validation >
<formset>
<form name="logonForm" >
<field property="userName“ depends="required,mask" >
<msg name=“mask”
key=“logon.username.maskmsg”/>
<arg0 key=“logon.username.displayname” />
<var>
<var-name>mask</var-name>
<var-value> ^[a-zA-Z0-9]*$</var-value>
</var>
…
Summary
Different levels of validation
Leveraging the validation framework
Pre-Defined Validators
Questions?
Struts Tiles
Presentation Agenda
Tiles Configuration
Tile Definitions and Extensions
Why Tiles
Frame look without frames
Consistent look across application
Reduce maintainance
A better way to “include” a JSP file
What is a Tile?
An area or region with in a web page.
Header
Left
Body
Nav
Footer
Configuration Requirements
Struts Configuration
– TilesRequestProcessor
– TilesPlugin
Tiles Definition XML File
Required Jars
– tiles.jar
– commons-digester.jar
– commons-beanutils.jar
– commons-collections.jar
– commons-logging.jar
TilesRequestProcessor
Extends the RequestProcessor to provide per
request processing of the forwards.
– Evaluates the forward to see if it is a tile
forward.
Required for Tiles to work
Struts-config.xml
<struts-config>
<controller
processorClass="org.apache.struts.tiles.TilesReques
tProcessor" />
</struts-config>
TilesPlugin
Checks to see that the configured controller is an
instance of the TilesRequestProcessor. If it is
not it will remove the request processor and
replace it with the TilesRequestProcessor.
Struts-Config.xml File
<plug-in
className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml" />
</plug-in>
Left Nav
Left
Body
Nav Body
Footer Footer
Define A Simple Layout
<html:html>
<head></head>
<body bgcolor="#ffffff">
<!--Header page information -->
<tiles:insert attribute="header"/> Layout Design
<br />
header
<!--Main body page information -->
<tiles:insert attribute="body"/>
body
<br />
<!--Footer page information -->
footer
<tiles:insert attribute="footer"/>
<br />
</body>
</html:html>
Understanding the Value of
Extends
Closer Look at the Tiles
Definition Extensions
The next set of slides demonstration an evolution
of thought.
The conclusion of which will be a model of how to
configure the tile-def.xml file.
Steps:
– Configuration of a definition
– Configuration of a 2nd definition
– 1st Example using extends
– The creation of an abstract definition
– Examples 1 and 2 refactored
Starting Definitions
Example1 Definition Example1 Definition
<definition name="example1“ <definition name="example2“
path="/Layout.jsp"> path="/Layout.jsp">
<put name="header" <put name="header"
value="/header.jsp"/> value="/header.jsp"/>
<put name="footer" <put name="footer"
value="/footer.jsp" value="/footer.jsp"
/> />
<put name="body" <put name="body"
value="/example1.jsp" /> value="/example2.jsp" />
</definition> </definition>
Tiles Definition Extension
By using the Extends attribute, a definition can
“inherit” all the “puts” of the inherited definition.
<tiles-definitions>
<definition name="example1" path="/Layout.jsp">
<put name="header" value="/header.jsp" />
<put name="footer" value="/footer.jsp" />
<put name="body" value="/example1.jsp" />
</definition>
<definition name="example2"
extends="example1">
<put name="body" value="/example2.jsp" />
</definition>
</tiles-definitions>
Abstract Definitions
A definition which by itself is very used. It
is not concrete.
– Meaning it doesn’t define everything
necessary to display a page.
Useful to refer to as one of the layout of the
site Notice there is no body defined.
<tiles-definitions>
<definition name="main" path="/Layout.jsp">
<put name="header" value="/header.jsp" />
<put name="footer" value="/footer.jsp" />
</definition>
Abstraction Use
<definition name="example1" extends="main">
<put name="body" value="/example1.jsp" />
</definition>
<definition name="example2" extends="main">
<put name="body" value="/example2.jsp" />
</definition>
</tiles-definitions>
Additional Configurations
Adding a Title to the Layout
<html:html>
<head>
<title> <tiles:getAsString name=“title”/></title>
</head>
<body bgcolor="#ffffff">
<!--Header page information -->
<tiles:insert attribute="header"/>
<br />
<!--Main body page information -->
<tiles:insert attribute="body"/>
<br />
…
Title Configuration
<definition name="example1" extends="main">
<put name=“title” value=“Example 1 Page”/>
<put name="body" value="/example1.jsp" />
</definition>
<definition name="example2" extends="main">
<put name=“title” value=“Example 2 Page”/>
<put name="body" value="/example2.jsp" />
</definition>
Action Forward to Tiles
Struts-config.xml file
<action input="/Login.jsp" name="logonForm"
path="/logon" scope="request“
type="com.codementor.LogonAction"
validate="true">
<forward name="success" path="example1" />
<forward name="failure" path="example2" />
</action>
<h1> <h1>
Successful Login Failed Login
</h1> </h1>
Tiles Configuration
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software
Foundation//DTD Tiles Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
<tiles-definitions>
<definition name="main" path="/Layout.jsp">
<put name="footer" value="/copyright.jsp" />
<put name="header" value="/header.jsp" />
<put name="body" />
</definition>
Tiles Config
<definition extends="main" name="login.page">
<put name="body" value="/Login.jsp" />
<put name="title" value="Logon Page" />
</definition>
<definition extends="main"
name="success.page">
<put name="body" value="/Success.jsp" />
<put name="title" value="Success Page" />
</definition>
<struts-config>
<form-beans> Struts-Config.xml
<form-bean name="formBean"
type="com.codementor.LogonForm" />
</form-beans>
<action-mappings>
<action path="/loginPage" forward="login.page"
/>
<action input="/loginPage.do" name="formBean"
path="/logon"
type="com.codementor.LogonAction">
<forward name="success"
path="success.page" />
<forward name="failure" path="failure.page" />
</action>
</action-mappings>
package com.codementor;
LogonForm
import org.apache.struts.action.*;