Title: DATA MINING
1http//www.jugtorino.it
STRUTS
Building Web Appication With Struts
Last changed November 06, 2002 Version 0.8
2Architecture evolution and strategies
3From HTTP to J2EE
Architecture evolution and strategies
Web application has evolved over the time from
simple static pages to more complex dynamic
server side interactions.
- Static pages
- Scripting technologies
- Dynamic server page generation
Anyway web applications are always based on HTTP
protocol and therefore they still use the same
type of interaction an HTTP response follows to
a HTTP request.
4Scripting
Architecture evolution and strategies
- Some kind of executables is launched when a new
request arrives - The script can delegate actions to other
subroutines or external services to return the
response - Servlet implements the same behavior in the Java
language with some other powerful capabilities
But
- the main drawback is resources consumption
- building HTTP response from scratch inside a
programming language (even if Java) is not
comfortable for programmers and nearly impossible
for web designers
5Server pages
Architecture evolution and strategies
Server pages take the problem from the other
side given an HTML skeleton fill it with
scripting code and let the code be transformed
into HTML when the page is requested.
Every change to the presentation doesn't need to
explicit recompile the code. But...
- Reuse is hard to obtain and maintainability is
more difficult - Control logic is implemented in too many pages
6A new approach
Architecture evolution and strategies
Java based web application can be divided in two
architectures
- In Model 1 architectures, client calls directly
JSP pages which forward the response to the next
page. - In Model 2 architecture, client calls Servlets
instead. Servlets check application conditions
and determine the correct flow
Servlets are the best choice for control the flow
of the application while JSP pages format the
response and nothing more.
7Domain tier
Architecture evolution and strategies
Domain tier is one of the possible tiers an
application can be divided into but not all
applications (web or other GUI) need domain
objects.
But often web application accesses some kind of
persistent information (both domain tier or
database directly) which needs to be changed at
every user interactions.
USER
MODEL
STATE
VIEW
8MVC
Architecture evolution and strategies
Model 2 architectures with a domain layer are
composed mainly of three components
- A Servlet Controller which receives request and
calls business logic to alter Model state. - A Model usually composed of persistent objects,
which represents application persistent
information. - A View, (normally more views) which describes the
interface for the user.
The whole mechanism was called Model View
Controller due to the similarity with the MVC
original idea.
There is a fundamental difference between "web"
MVC and "pattern" MVC HTTP protocol is stateless
and doesn't provide a mechanism by which the
model state can determine the next view directly.
9Implementing MVC
Architecture evolution and strategies
- There are basically two ways of implementing MVC
- With a single front controller and a single entry
point in the application. - With more than one page controller and many entry
points.
The first is commonly known as Front Controller
pattern and the second Page Controller pattern.
10Page Controller
Architecture evolution and strategies
There is a controller for each page in the web
application or, saying it better, one controller
for each action in the application.
public class SomeActionController extends
ControllerServlet protected void
doPost(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException
SomeDTO someDtonull String
theRequestedNamereq.getParameter("name")
/ theRequestedName can be null. Method
findNamed checks for this. If dto doesn't
exist the method rises an exception. /
try someDto SomeDTO.findNamed(the
RequestedName) catch (DomainObjectNotFound
e) / The output is redirected to the
correct error page. The forward method
generates an ApplicationException which is
propagated through the container and
managed outside the program into the xml
descriptor. / String msg"
SomeActionController doPut() - The requested
object was not found." super.forward("/Obj
ectNotFoundError.jsp",req,resp) /
Saving the result inside the context attributes.
Parameters can be only of string type
while attributes are ordinary objects inside an
hash./ req.setAttribute("someDto",
someDto) / Now it is time to send the
control to the correct view to display
Artist data correctly. / super.forward("/arti
st.jsp",req,resp)
11Front Controller
Architecture evolution and strategies
Front Controller is similar to Page Controller
but there is only one control point for each
action in the web application. As before, this
solution is best implemented using Servlets.
- First problem we need a mechanism to tell the
Servlet the action we want because the address
doesn't represent now any physical resource. - Second problem transforming Strings
representation of action into running code.
12Front Controller / Problem n1
Architecture evolution and strategies
There are some options
- We store the action inside POST hidden fields.
- The same as before but using GET parameters
instead of POST fields. - Using mapping possibilities of web.xml descriptor.
- Solution 3 seems to be the more attractive the
mapping here is declarative and therefore more
manageable - ltservlet-mappinggt
- ltservlet-namegtmyServletlt/servlet-namegt
- lturl-patterngt.dolt/url-patterngt
- lt/servlet-mappinggt
13Front Controller / Problem n2
Architecture evolution and strategies
- When the request is received by the Servlet, a
String type action has to be translated into a
business action. The obvious and easier solution
is to implement an if statement -
- if (op.equals("createUser"))
- model.createUser(request.getAttribute("user"
), - request.getAttribute("pass"))
- else if (op.equals("changeUserInfo")
- // ... and so on...
-
The solution is difficult to maintain and could
be also complex to read if the number of possible
actions rise. This common problem has also a
common solution which is called Command Pattern
1.
14 Architecture evolution and strategies
Command Pattern
- Construct an interface with an execute() method
inside. - Construct an object implementing the interface
for each action. - Implement execute() method to perform business
logic operation needed. - Let the Servlet dynamically instantiates the
object representing the action to do. - Let the Servlet calls execute() and receives the
results.
15Other problems, tips and tricks
16Labels, messages and I18N
Other problem, tips and tricks
It is common when building application to
externalize strings. The obvious reason to do
that is to decoupling code from presentation
strings used both on "fat" clients as "thin"
(like web pages).
- Java gives us Message Bundle mechanism. Using
MessageBundle class it is possible to create a
more manageable system to fill message at
runtime. - // Load the resource bundle
- ResourceBundle bundle ResourceBundle.getBundle
( "ApplicationResources" ) - // Get the message template
- String requiredFieldMessage bundle.getString(
"error.requiredfield" )
17Exception Handling
Other problem, tips and tricks
Its not a good idea to send in front of the user
message as "Error 500 Internal Server Error" and
the following stack trace. Programmers have
always to catch exception and presenting them as
easy to read message. J2EE web application, for
example, can declaratively describe (web.xml
file) actions to be taken when exception are
thrown. Although J2EE manages exception, J2EE
doesn't manage messages auto-describing errors
and multiple exceptions in a single thrown.
18Filling form data
Other problem, tips and tricks
Another common activity web programmers are
facing with is to move data from client browser
to presentation or business tier. This is common
with HTML form
- The user fills HTML form.
- Data are sent through POST command inside the web
container. - Program extracts data with getAttribute() calls.
- Fill some DTOs
- Send information to domain tier to alter the
state.
Moreover information has to be validated.
19Validation
Other problem, tips and tricks
Since all data that is retrieved from a request
is of type String, you must ensure that the data
is not going to corrupt your business components.
Validation is about data control and checking
against some business rules. Validation can be
performed inside presentation tier or domain tier
depending on particular application.
20Struts frameworks in detail
21Well, yeah, and Struts?
Struts framework in detail
Struts, like many other frameworks and web
utilities, is the place where all best practices,
experiences and patterns converge at the end. You
can think at Struts as a products that summarize
quite all experiences done building web
application.
Front Controller
I18N
Tag Library
Command Pattern
MVC
Exception Handling
Data Transport
STRUTS
22Action Servlet
Struts framework in detail
- Struts implements a Model 2 architecture with a
Front Controller approach. The controller is
called ActionServlet which is of course a
Servlet. The Servlet comes with the framework
you dont need to build one your self. But you
have to configure it inside web.xml - ltservletgt
- ltservlet-namegtactionlt/servlet-namegt
- ltservlet-classgtorg.apache.struts.action.Action
Servletlt/servlet-classgt - ltinit-paramgt
- ltparam-namegtdebuglt/param-namegt
- ltparam-valuegt5lt/param-valuegt
- lt/init-paramgt
- ltinit-paramgt
- ltparam-namegtconfiglt/param-namegt
- ltparam-valuegt/WEB-INF/struts-config.xmllt/par
am-valuegt - lt/init-paramgt
- ltinit-paramgt
- ltparam-namegtdetaillt/param-namegt
- ltparam-valuegt3lt/param-valuegt
- lt/init-paramgt
- ltload-on-startupgt2lt/load-on-startupgt
- lt/servletgt
23Url mappings
Struts framework in detail
The ActionServlet receives request from container
using url mappings. As before this is declared
inside web.xml ltservlet-mappinggt
ltservlet-namegtactionlt/servlet-namegt
lturl-patterngt.dolt/url-patterngt lt/servlet-mappinggt
Here we have that every address ending in .do
will be routed to the ActionServlet. Neither use
of hidden fileds in POST nor GET parameters.
24Actions 1/3
Struts framework in detail
Actions in Struts have a special meaning. They
are nothing more that Commands (do you remember
Command Pattern?). Their role is to implement
user requests as objects lta href"/pefWAR/retrie
veAllMessages.do?actionprepareCreateSubject"gtnuov
o soggettolt/agt When requests arrive, the web
container routes the call to ActionServlet. How
ActionServlet knows what piece of business logic
to call? ActionServlet could try to istantiate an
Action called RetrieveAllMessage and then call
execute() method on it. But Struts adds another
level of indirection.
25Actions 2/3 Struts Config
Struts framework in detail
- Together with web.xml descriptor, Struts has its
own internal descriptor called normally
struts-config.xml. Settings inside the file
produce different behaviors, as in the case of
incoming Action - ltaction path"/retrieveAllSubjects"
- type"datel.action.RetrieveAllSubje
ctsAction" - scope"request"
- validate"false"gt
- ltforward name"goToMain" path"/admin/allSub
jects.jsp"/gt - ltforward name"goToCreateMessage"
path"/admin/createMessage.jsp"/gt - lt/actiongt
- Here, a request ending in .do and beginning with
retrieveAllSubjects brings to the execute() call
on RetrieveAllSubjectsAction instance to change
referred action, simply change descriptor.
26Actions 3/3 Forwarding Results
Struts framework in detail
After ActionServlet has called execute(), how
does it know which views to display next? In
other word, different model states led to
different views. Struts brings this decision
outside the code, in struts-config. ltaction
path"/retrieveAllSubjects" gt ltforward
name"goToMain" path"/admin/allSubjects.jsp"/gt
ltforward name"goToCreateMessage"
path"/admin/createMessage.jsp"/gt lt/actiongt
The above forwards tell Struts what to do when
from the code there is a
mapping.findForward("goToMain")
To change application flow, simply add or change
forward inside descriptor.
27Resource bundle support
Struts framework in detail
Struts uses underneath the JDK standard
ResourceBoundle utility adding some enhancements.
- ResourceBundle management inside struts-config,
declaratively - Support for multiple ResourceBoundle
- Access facilities from taglib and framework
classes (ActionMessage, ActionError)
ltmessage-resources parameter"ApplicationResources
"/gt ltmessage-resources key"IMAGE_RESOURCE_KEY"
parameter"ApplicationImageResources"/gt
28Exception handling 1/2
Struts framework in detail
Starting with Struts version 1.1, exceptions can
propagate freely up to the container. Programmer
can manage them declaratively inside
struts-conifg, like this
ltexception key"global.error.invalidlogin"
path"/login.jsp" scope"request"
type"com.oreilly.struts.banking.service.InvalidLo
ginException"/gt
Here if InvalidLoginException is thrown by any
action, it should be forwarded to the login.jsp
resource and built an error message using the key
global.error.invalidlogin from the resource
bundle.
J2EE vs. Struts there is support for
automatically manage exception description (in
conjunction with taglib).
29Exception handling 2/2
Struts framework in detail
Struts can handle automatically error messages
displaying them back to the user in a single
structure called ActionErrors. ActionErrors is a
container for ActionError elements.
ActionErrors errors new ActionErrors() errors.a
dd("email", new ActionError("security.error.email.
required")) errors.add("password", new
ActionError("security.error.password.required"))
The String argument passed into the constructor
of the ActionError class must be a key in the
resource bundle. Then access ActionErrors from
taglib
lthtmlerrors/gt
J2EE vs. Struts many exceptions - a single
ActionErrors to fill and display in a single line.
30Moving data, ActionForms 1/3
Struts framework in detail
Struts gives programmers the possibility to
automatically retrieve form data and store them
in a Bean
ltform-bean name"messageForm"
type"datel.domain.MessageDTO"/gt
Name of bean properties and form fields must
coincide. ActionForm can be accessed from Actions
public ActionForward execute(ActionMapping
mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
String username(String)PropertyUtils.getSimpl
eProperty(form,"username") String
password(String)PropertyUtils.getSimpleProperty(f
orm,"password") // or // MessageDTO
messageDTO(MessageDTO)form
31Validation, ActionForms 2/3
Struts framework in detail
ActionForm can be also the right place for data
validation. You can optionally override method
validate() and let Struts calls it before
accessing the ActionForm from Action classes.
Its a good idea to implement method reset()
also. Inside reset() programmers must ensure that
all bean attributes are reset to their default
state. Struts calls reset() method every time it
reuses ActionForm instance instead of building a
new one.
32DynaActionForms 3/3
Struts framework in detail
Creating new ActionForms for every HTML form in
your application can be a daunting task. You can
reuse them when possible or create them
dynamically
ltform-bean name"logonForm" type"org.apache.strut
s.action.DynaActionForm"gt ltform-property
name"username" type"java.lang.String"/gt
ltform-property name"password" type"java.lang.Str
ing"/gt lt/form-beangt
Here Struts materializes for us a new brand Bean
with two attributes (username and password),
getters and setters and a reset() method.
33How to define ActionForms
Struts framework in detail
You can define ActionForms inside
struts-config.xml
ltaction path"/logon" type"datel.action.Logon
Action" name"logonForm" scope"request"
input"/admin/logon.jsp"gt lt/actiongt
If client requests an url as /something/login.do
Struts istantiates or reuses an ActionForm called
logonForm (see previous slide), fills it with
posted information and passes it as argument of
execute() method call.
34Struts pre-built extensions and utilities
35Many type of actions
Struts pre-built extensions and utilities
- ForwardAction when you only need to perform a
forward - IncludeAction when you only need to perform an
include - DispatchAction to reuse the same Action with
slightly different behavior - LookupDispatchAction same as Dispatch adding a
ResourceBundle lookup to find the right action. - SwitchAction to switch control between different
web context
36The util package
Struts pre-built extensions and utilities
General purpose classes to solve common problems
in Struts web application developing. Here the
most important
- IteratorAdapter helps converting Enumeration to
Iterator interface - RequestUtil thread-safe operation on Request
objects - ResponseUtil the same on Response objects
- StrutsValidator common pre-built validation
method
37The apache.common package
Struts pre-built extensions and utilities
Not properly a Struts package, but Struts makes a
frequent use of these utilities. Here the most
used features
- BeanUtils common method to manage beans
(populate, getProperty) - Collections improvement on the standard JDK 1.3
package (FlashHashMap)
38Struts tag libraries
39Brief description
- Bean manages property, creation and output of
JavaBeans - Html wrapping HTML into tags
- Logic perform flow instructions (iteration,
if-then) - Nested same as Bean, Html and Logic when used in
nested context - Template everything necessary to manage page
templates.
40CONCLUSIONS
41Whats next?
- Struts extension points
- Struts tag libraries
42References
References
- 1 http//hillside.net/patterns/books/DPBook/DPB
ook.html, is a link to a description of the well
known book by the Gang of Four called "Design
Pattern, Elements of Reusable Object-Oriented
Software". It contains pattern description like
MVC. - 2 http//martinfowler.com/isa/index.html, è il
libro di Martin Fowler prossimo all'uscita che
spiega le motivazioni alla base dei pattern
scelti. - 3 http//www.theserverside.com/books/EJBDesignP
atterns/index.jsp, è il libro di Floyd Marinescu
sulle best practices della programmazione EJB.
Molti pattern rappresentano ad ogni modo stilemi
di buona programmazione applicabili in altri
contesti. Il libro è scaricabile previa piccola
registrazione. - 4 Designing Enterprise Applications, alias
J2EE Blueprints, è il testo di riferimento SUN
per quanto riguarda le best practices da tenere
nello sviluppo di applicazioni enterprise. Il
testo è corredato dall'applicazione di esempio
PetStore dove i pattern vengono realmente
implementati.