Professional Documents
Culture Documents
Framework
Agenda
STRUTS
JSP Model 1
Architecture
Model 2 (MVC)
Architecture
MVC - Model
In the MVC design pattern, the Model provides access to the
necessary business data as well as the business logic needed to
manipulate that data.
The Model typically has some means to interact with persistent
storage such as a database to retrieve, add, and update the
data.
The Model can be built up with Simple Java Beans or EJB or
WebServices
MVC - Controller
The Controller handles all requests from the user and selects the view to
return.
When the Controller receives a request, the Controller forwards the request to
the appropriate handler, which interprets what action to take based on the
request.
The Controller calls on the Model to perform the desired function.
After the Model has performed the function, the Controller selects the View to
send back to the user based on the state of the Models data.
MVC - View
The View is responsible for displaying data from the Model to the
user.
This layer also sends user data to the Controller.
In the case of a Web application, this means that both the request
and the response are in the domain of the View.
Model2
(MVC) Architecture
1. Controller Servlet handles the users request.
10
Servlet
4. Get result &
set in scope
<<Model>>
Datastore
Browser
JavaBeans
5. Dispatch to
next view
6. Response
Uses
<<View>>
JSP
1.
11
3. Connect to
Database &
get/save data
Advantages of MVC
Greater flexibility:
Its easy to add different View types (HTML, XML) and interchange
varying data stores of the Model because of the clear separation of
layers in the pattern.
Best use of different skill sets:
Designers can work on the View, programmers more familiar with data
access can work on the Model, and others skilled in application
development can work on the Controller. Differentiation of work is
easier to accomplish because the layers are distinct.
Ease of maintenance:
The structure and flow of the application are clearly defined, making
them easier to understand and modify. Parts are loosely coupled with
each other.
12
What is Struts
13
Struts
advantages
14
15
16
STRUTS
A Framework
3. Invoke
reset and
validate
Action
Servlet
1. HTTP
Request
2. Read
mappings
Struts-config.xml
17
Action
Form
4. Return
Errors
5. Invoke execute method
6. Return forward action
7. Forward to
appropriate View
Presentation
(JSP)
Action
Class
Struts
Components
18
ActionServlet
The central component of the Struts Controller is the
ActionServlet.
ActionServlet performs two important things
On startup it reads the Struts Configuration file and loads it into
memory in the init() method.
In doGet() or doPost() methods it intercepts HTTP request and
handles the appropriately.
19
RequestProcessor
After ActionServlet has intercepted the HTTP request, it delegates
the request handling to RequestProcessor.
The process() of the RequestProcessor does the following :
The RequestProcessor first retreives the ActionMappings
from struts-config.xml.
From ActionMappings it gets the name of ActionForm and
populates it if it is already created otherwise creates it first.
Next if some validations are required on the input, that is done
Lastly the execute() method of Action class is invoked.
The RequestProcessor is specified in struts-config.xml as
<controller processorClass =
"org.apache.struts.action.RequestProcessor"/>
21
ActionForm
ActionForm is essentially a JavaBean with a list of private
attributes and a pair of getXXX() and setXXX() method for each
of the attributes.
Struts application extends the ActionForm class to implement its
own.
RequestProcessor instantiates the ActionForms subclass and
puts it in appropriate scope.
Next RequestProcessor iterates through the HTTP request
parameters and populates the matching attributes.
Next if validation is enabled the validate() method is called.
23
ActionForm class
24
STRUTS
25
ActionForm Lifecycle
Action
The RequestProcessor instantiates the Action class specified in the
ActionMapping and invokes the execute() method.
The signature of execute() is
26
Action (contd)
We should have our own class which extends the Action class
public class NameAction extends Action {
public ActionForward execute (ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception{
NameForm nform = (NameForm) form;
System.out.println(In NameAction ::execute());
return mapping.findForward("success");
}
}
27
ActionForward
ActionForward is the class that encapsulates the next view information.
ActionForward encapsulates the association of the logical name and
the physical JSP page.
The logical name and physical page is specified in the strutsconfig.xml file.
<forward name="success" path = "/Success.jsp" />
After successful execution the execute() method of Acton class returns
the appropriate ActionForward.
return mapping.findForward("success");
The ActionForward can be either local to one ActionMapping or
global.
28
struts-config.xml
struts-config.xml is the primary configuration file for the
Controller.
Five important sections in struts-config.xml are:
1.
2.
3.
4.
5.
29
struts-config.xml
Form bean definition section
The form bean definition section contains one or more entries
for each ActionForm.
Each form bean is identified by an unique logical name.
Type is the fully qualified class name of the ActionForm.
<form-beans>
<form-bean name="NameForm
type="app1.NameForm"/>
</form-beans>
30
struts-config.xml
Attribute/Element
Path
Type
Name
Scope
Validate
Input
Forward
31
Description
The URL path
The Action class name.
The logical name of the Form
bean
Scope of the Form bean
If true the form bean is validated
The page to which the control will be
forwarded in case of an error.
The physical page/another ActionMapping
to which the control should be forwarded
when ActionForward with this name is
selected in the execute method of the
Action class.
name="NameForm
type="app1.NameForm"/>
</form-beans>
<action-mappings>
<action
path="/NameSubmit"
type="app1.NameAction"
name="NameForm"
scope="request"
validate="true"
input="/Name2.jsp">
<forward name="success" path = "/Success.jsp" />
<forward name="failure" path ="Failure.jsp" />
</action>
</action-mappings>
</struts-config>
32
struts-config.xml
Global forward definition section
Unlike, local forwards Global Forward section is
accessible from any ActionMapping.
<global-forwards>
<forward name=logon path=/logon.jsp/>
</global-forwards>
33
Model
Components
34
View
Components
36
STRUTS
View Components
37
STRUTS Tag
Libraries
38
STRUTS
Tag Libraries
39
HTML
<html:html></html:html>
The tags Tags
in the Struts HTML library form a bridge
between a JSP view and the other components of a Web
application.
40
HTML tags
<html:base/>
41
HTML Tags
<html:form></html:form>
</html:form>
42
HTML tags
<html:text/>,<html:submit>
43
</HTML>
<HTML:HTML>
<BODY>
<HTML:FORM action="/CustomerForm >
<TABLE WIDTH="100%">
<TD><html:text property="name" size="40" maxlength="40" /></TD></TR>
<TD>< html:text property="address" size ="40" maxlength ="40" /></TD></TR>
<TD>< html:text property="city" size ="20" maxlength ="20" /></TD></TR>
</TABLE>
</HTML:FORM>
</BODY>
45
</HTML:HTML>
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
46
Logic Tags
47
Logic Tags
Tag Name
Description
empty
equal
forward
greaterEqual
greaterThan
iterate
lessEqual
lessThan
match
messagesNotPresent
messagesPresent
notEmpty
notEqual
notMatch
notPresent
present
48
redirect
Evaluate the nested body content of this tag if the requested variable is either null or an empty string.
Evaluate the nested body content of this tag if the requested variable is equal to the specified value.
Forward control to the page specified by the specified ActionForward entry.
Evaluate the nested body content of this tag if requested variable is greater than or equal to specified value.
Evaluate the nested body content of this tag if the requested variable is greater than the specified value.
Repeat the nested body content of this tag over a specified collection.
Evaluate the nested body content of this tag if requested variable is greater than or equal to specified value.
Evaluate the nested body content of this tag if the requested variable is less than the specified value.
Evaluate the nested body content of this tag if specified value is an appropriate substring of requested
variable.
Generate the nested body content of this tag if the specified message is not present in this request.
Generate the nested body content of this tag if the specified message is present in this request.
Evaluate the nested body content of this tag if the requested variable is neither null nor an empty string.
Evaluate the nested body content of this tag if the requested variable is not equal to the specified value.
Evaluate the nested body content of tag if specified value not an appropriate substring of requested variable.
Generate the nested body content of this tag if the specified value is not present in this request.
Generate the nested body content of this tag if the specified value is present in this request.
</TABLE>
50
STRUTS
View Components
51
STRUTS
View Components
STRUTS
View Components
54
Application
Resource File
55
56
ApplicationResources.properties
prompt.firstName = First Name
prompt.lastName = Last Name
button.save = Save Me
button.cancel = Cancel Me
errors.header=<h3><font color="red">Validation
Error</font></h3>
Plz rectify the following error:<ul>
errors.footer=</ul><hr>
error.firstName.null = First Name is required
57
Handling Errors
59
60
validate() method
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request){
ActionErrors errors = new ActionErrors();
if(firstName == null || firstName.trim().equals(""))
{
errors.add("firstName",new
ActionError("error.firstName.null"));
}
return errors;
}
61
Exception Handling
62
63
64
65
STRUTS
Exception Handling
<exception
key=error.NoResultsFoundException"
path="/exception.jsp"
handler=com.oreily.struts.ExceptionHandler
type=com.jamesholmes.minihr.NoResultsFoundException"/>
</action>
</action-mappings>
</struts-config>
66
STRUTS
Exception Handling
Sequence of Events
The RequestProcessor class executes its
processException() method.
Finds the Exception in the action mapping
The default exception handler creates and stores an
ActionError into the specified scope and gives the control
to the resource specified in the path attribute
67
STRUTS
Exception Handling
68
STRUTS
Exception Handling
69
STRUTS
Exception Handling
70
Validator Framework
71
STRUTS
Validator Framework
STRUTS
Validator Framework
STRUTS
Validator Framework
Validation-rules.xml
<validator
name=required
classname="org.apache.struts.util.StrutsValidator"
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">
</validator>
74
STRUTS
Validator Framework
75
STRUTS
Validator Framework
The resource bundle should have the following default key-value pairs.
errors.required={0} is required.
errors.minlength={0} cannot be less than {1} characters.
errors.maxlength={0} cannot be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
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 email address
76
STRUTS
Validator Framework
Validation.xml
This file is application specific
It defines which validation rules from the validationrules.xml are used by a particular ActionForm
The validation logic is associated with one or more
ActionForm classes through this external file.
77
78
STRUTS
Validator Framework
<formset>
<form name="checkoutForm">
<field property="phone depends="required,mask">
<arg0 key="registrationForm.firstname.displayname"/>
<var>
<var-name>mask</var-name>
<var-value>${phone}</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
79
STRUTS
Validator Framework
80
STRUTS
Validator Framework
81
82
STRUTS
Each tile is just a web page in its own right & theyll all be inserted where you
want them.
This model promotes reusability.
If the only thing that changes between the 500 web pages on your site is the
individuals pages body and you want to keep the header, footer and a navigation
menu the same for each page , Tiles can help you a lot
Header
Menu
Body
Footer
83
84
85
Struts
Resources
Struts Book
Struts Essential Skills Steven Holzner
Struts Complete Reference James Holmes , Schildt
Struts User Guide
http://jakarta.apache.org/struts/userGuide/index.html
87
Questions
88
89