unit 07: design patterns and frameworks (3/3)
DESCRIPTION
TRANSCRIPT
1 dsbw 2011/2012 q1
A framework “is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality.” (from Wikipedia)
Here we are going to consider 3 MVC-based Web frameworks for Java:
Struts 1
Spring MVC
JavaServer Faces
Unit 7: Design Patterns and Frameworks
2 dsbw 2011/2012 q1
Struts 1: Overview
3 dsbw 2011/2012 q1
4 dsbw 2011/2012 q1
5 dsbw 2011/2012 q1
Struts 1: Terminology wrt. J2EE Core Patterns
Struts 1
Implementation
J2EE Core Patterns
Concept
ActionServlet Front Controller
RequestProcessor Application Controller
UserAction Businesss Helper
ActionMapping View Mapper
ActionForward View Handle
6 dsbw 2011/2012 q1
Struts 1: Example - WoT’s New User
7 dsbw 2011/2012 q1
<html><head> .... </head>
<body>
…
<form action = “register.do" method="post">
User’s Nickname:
<input name=“username" value="$!registrationForm.username" size=40> $!errors.wrongUsername.get(0)
Password :
<input name=“userpassword“ size=40> $!errors.wrongPassword.get(0)
<!–- CAPTCHA CODE -->
<input type="submit" name="insert" value=“insert">
</form>
<center>$!errors.regDuplicate.get(0)</center>
</body></html>
Struts 1: Example – user_registration.vm (Velocity template)
8 dsbw 2011/2012 q1
Struts 1: Example – Form validation
9 dsbw 2011/2012 q1
public class RegistrationForm extends ActionForm
{
protected String reg_username;
// ... The remaining form attributes + getter & setter methods
public void reset(ActionMapping mapping,
HttpServletRequest request) {
/* ... Attribute initialization */ }
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (reg_username == null || reg_username.equals("")) {
errors.add(“wrongUsername",
new ActionMessage("errors.username”));
}
// .... Remaining validations
return errors; }
}
Struts 1: Example - RegistrationForm
10 dsbw 2011/2012 q1
errors.username=(*) Username required
errors.password=(*) Password required
errors.regCAPTCHA=(*) Invalid CAPTCHA values
errors.duplicateUser = Username '{0}' is already taken by
another user
Struts 1: Example – Error Messages (Message.properties file)
11 dsbw 2011/2012 q1
Struts 1: Example – Application Error (duplicated username)
12 dsbw 2011/2012 q1
public class RegisterAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
{ String username = ((RegistrationForm) form).getReg_username();
String password = ((RegistrationForm) form).getReg_password();
Connection dbConnection = … ;
try {
Transaction trans = Transaction.newTransaction("RegisterTrans");
trans.getParameterMap().put("dbConnection", dbConnection);
trans.getParameterMap().put("username", username);
trans.getParameterMap().put("password", password);
trans.execute();
request.getSession().setAttribute("loggedUserNAME",username);
request.getSession().setAttribute("loggedUserID",trans.getPara
meterMap().get("userID"));
return (mapping.findForward("success"));
}
Struts 1: Example - UserAction
13 dsbw 2011/2012 q1
catch (BusinessException ex)
{
if (ex.getMessageList().elementAt(0).startsWith("Username"))
{
ActionMessages errors = new ActionMessages();
errors.add("regDuplicate",
new ActionMessage("errors.duplicateUser",username));
this.saveErrors(request, errors);
form.reset(mapping,request);
return (mapping.findForward("duplicateUser"));
}
else {
request.setAttribute("theList",ex.getMessageList());
return (mapping.findForward("failure"));
}
}
}
}
Struts 1: Example – UserAction (cont.)
14 dsbw 2011/2012 q1
<action-mappings>
<action path="/register"
type="woTFront.RegisterAction"
name="registrationForm"
scope="request"
validate="true"
input="/user_registration.vm">
<forward name="failure" path="/error.vm"/>
<forward name="duplicateUser“ path="/user_registration.vm"/>
<forward name="success" path="/wall" redirect="true"/>
</action>
…
</action-mappings>
Struts 1: Example - struts-config.xml (fragment)
15 dsbw 2011/2012 q1
<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>
Struts 1: Example - web.xml (fragment)
16 dsbw 2011/2012 q1
<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>
org.apache.velocity.tools.view.servlet.VelocityViewServlet
</servlet-class>
<init-param>
<param-name>org.apache.velocity.toolbox</param-name>
<param-value>/WEB-INF/toolbox.xml</param-value>
</init-param>
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/velocity.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
Struts 1: Example - web.xml (fragment, cont.)
17 dsbw 2011/2012 q1
Struts 2 vs Struts 1 (according to struts.apache.org/2.x) Enhanced Results - Unlike ActionForwards, Struts 2 Results can
actually help prepare the response.
Enhanced Tags - Struts2 tags don't just output data, but provide stylesheet-driven markup, so that we consistent pages can be created with less code.
POJO forms - No more ActionForms: we can use any JavaBean we like or put properties directly on our Action classes.
POJO Actions - Any class can be used as an Action class. Even the interface is optional!
First-class AJAX support - The AJAX theme gives interactive applications a boost.
Easy-to-test Actions – Struts 2 Actions are HTTP independent and can be tested without resorting to mock objects.
Intelligent Defaults - Most framework configuration elements have a default value that we can set and forget.
Struts 2
18 dsbw 2011/2012 q1
Struts 2: Tagging example
<s:actionerror/>
<s:form action="Profile_update" validate="true">
<s:textfield label="Username" name="username"/>
<s:password label="Password" name="password"/>
<s:password label="(Repeat) Password" name="password2"/>
<s:textfield label="Full Name" name="fullName"/>
<s:textfield label="From Address" name="fromAddress"/>
<s:textfield label="Reply To Address" name="replyToAddress"/>
<s:submit value="Save" name="Save"/>
<s:submit action="Register_cancel" value="Cancel" name="Cancel" onclick="form.onsubmit=null"/> </s:form>
19 dsbw 2011/2012 q1
Spring's own implementation of the Front Controller Pattern
Flexible request mapping and handling
Full forms support
Supports several view technologies
JSP/Tiles, Velocity, FreeMarker
Support integration with other MVC frameworks
Struts, Tapestry, JavaServerFaces, WebWork
Provides a JSP Tag Library
Spring MVC
20 dsbw 2011/2012 q1
Spring Framework Architecture
Spring AOP AOP infrastructure
Metadata support
Declarative transaction
management
Spring Core
IoC Container
Spring ORM Hibernate support
iBatis support
JDO support
Spring Web WebApplicationContext
Struts integration
Tiles integration
Web utilities
Spring DAO Transaction Infrastructure
JDBC support
DAO support
Spring Context ApplicationContext
JNDI, EJB support
Remoting
Spring MVC Web MVC Framework
JSP support
Velocity/FreeMarker
support
PFD/Excel support
21 dsbw 2011/2012 q1
Spring MVC: Request Lifecycle
22 dsbw 2011/2012 q1
Spring MVC: Terminology wrt. J2EE Core Patterns
Spring MVC J2EE Core Patterns
Concept
DispatcherServlet Front Controller /
Application Controller
HandlerMapping Command Mapper
ModelAndView View Handle /
Presentation Model
ViewResolver View Mapper
Controller Business Helper
23 dsbw 2011/2012 q1
1. Add the Spring dispatcher servlet to the web.xml
2. Configure additional bean definition files in web.xml
3. Write Controller classes and configure them in a bean definition file, typically META-INF/<appl>-servlet.xml
4. Configure view resolvers that map view names to to views (JSP, Velocity etc.)
5. Write the JSPs or other views to render the UI
Spring MVC: Setting Up
24 dsbw 2011/2012 q1
public class ListCustomersController implements Controller {
private CustomerService customerService;
public void setCustomerService(CustomerService
customerService)
{ this.customerService = customerService; }
public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse res) throws Exception
{
return new ModelAndView(“customerList”, “customers”,
customerService.getCustomers());
}
}
ModelAndView object is simply a combination of a named view and a Map of objects that are introduced into the request by the dispatcher
Spring MVC: Controllers
25 dsbw 2011/2012 q1
Interface based
Do not have to extend any base classes (as in Struts)
Have option of extending helpful base classes
Multi-Action Controllers
Command Controllers
Dynamic binding of request parameters to POJO (no ActionForms)
Form Controllers
Hooks into cycle for overriding binding, validation, and inserting reference data
Validation (including support for Commons Validation)
Wizard style controller
Spring MVC: Controllers (cont.)
26 dsbw 2011/2012 q1
Sun’s “Official” Java-based Web application framework
Specifications:
JSF 1.0 (11-03-2004)
JSF 1.1 (25-05-2004)
JSF 1.2 (11-05-2006)
JSF 2.0 (28-06-2009)
Main characteristics:
UI component state management across requests
Mechanism for wiring client-generated events to server side application code
Allow custom UI components to be easily built and re-used
A well-defined request processing lifecycle
Designed to be tooled
JavaServer Faces (JSF)
27 dsbw 2011/2012 q1
JSF: Application Architecture
JSF Framework
Business Objects
Model Objects
JSF Application
Servlet Container
DB
EJB Container
Client Devices
Phone
PDA
Laptop
28 dsbw 2011/2012 q1
JSF framework: MVC
FacesServlet
Action
Handlers
& Event
Listeners
Config
Component
Tree Model Objects
Managed JavaBeans
Delegates Converters
Validators
Renderers
Resources JavaBeans
Property Files
XML
Business Objects EJB
JDO
JDBC
Controller Model
View
Request Response
29 dsbw 2011/2012 q1
JSF: Request Processing Lifecycle
Restore Component
Tree
Apply Request Value
Process Events
Process Validations
Render Response
Invoke Application
Update Model Values
Request
Response
Render Response
Conversion Errors
Process Events
Response Complete Response Complete
Process Events
Process Events
Response Complete Response Complete
Validation or Conversion Errors
30 dsbw 2011/2012 q1
Restore Component Tree:
The requesting page’s component tree is retrieved/recreated.
Stateful information about the page (if existed) is added to the request.
Apply Request Value:
Each component in the tree extracts its new value from the request parameters by using its decode method.
If the conversion of the value fails, an error message associated with the component is generated and queued .
If events have been queued during this phase, the JSF implementation broadcasts the events to interested listeners.
Process Validations: The JSF implementation processes all validators registered on
the components in the tree. It examines the component attributes that specify the rules for the validation and compares these rules to the local value stored for the component.
JSF: Request Processing Lifecycle
31 dsbw 2011/2012 q1
Update Model Values:
The JSF implementation walks the component tree and set the corresponding model object properties to the components' local values.
Only the bean properties pointed at by an input component's value attribute are updated
Invoke Application:
Action listeners and actions are invoked
The Business Logic Tier may be called
Render Response:
Render the page and send it back to client
JSF: Request Processing Lifecycle
32 dsbw 2011/2012 q1
JSF: Anatomy of a UI Component
UIComponent
Child UIComponent
Id Local Value
Attribute Map
Event Handling
Validators has
has
has
has
Render
has
Converters
has
Model
binds
33 dsbw 2011/2012 q1
UIInput
UIOutput
UISelectBoolean
UISelectItem
UISelectMany
UISelectOne
UISelectMany
UIGraphic
JSF: Standard UI Components
UICommand
UIForm
UIColumn
UIData
UIPanel
34 dsbw 2011/2012 q1
JSF Core Tag Library (prefix: f)
Validator, Event Listeners, Converters
JSF Standard Library (prefix: h)
Express UI components in JSP
JSF: HTML Tag Library
35 dsbw 2011/2012 q1
JSF: HTML Tag Library
<f:view>
<h:form id=”logonForm”>
<h:panelGrid columns=”2”>
<h:outputLabel for=”username”>
<h:outputText value=”Username:”/>
</h:outputLabel>
<h:inputText id=”username”
value=”#{logonBean.username}”/>
<h:outputLabel for=”password”>
<h:outputText value=”Password:”/>
</h:outputLabel>
<h:inputSecret id=”password”
value=”#{logonBean.password}”/>
<h:commandButton
id=”submitButton” type=”SUBMIT”
action=”#{logonBean.logon}”/>
<h:commandButton
id=”resetButton” type=”RESET”/>
</h:panelGrid>
</h:form>
</f:view>
36 dsbw 2011/2012 q1
Used to separate presentation from business logic
Based on JavaBeans
Similar to Struts ActionForm concept
Can also be registered to handle events and conversion and validation functions
UI Component binding example:
<h:inputText id=”username” value=”#{logonBean.username}”/>
JSF: Managed (Model) Bean
37 dsbw 2011/2012 q1
New Page Declaration Language (PDL) based on Apache Facelets
Custom components much easier to develop
Improved Ajax integration and support
What’s new in JSF 2.0?
38 dsbw 2011/2012 q1
Books:
B. Siggelkow. Jakarta Struts Cookbook. O'Reilly, 2005
J. Carnell, R. Harrop. Pro Jakarta Struts, 2nd Edition. Apress, 2004
C. Walls, R. Breidenbach. Spring in Action. Manning, 2006.
B. Dudney, J. Lehr, B. Willis, L. Mattingly. Mastering JavaServer Faces. Willey, 2004.
Web sites:
struts.apache.org
rollerjm.free.fr/pro/Struts11.html
www.springframework.org
static.springframework.org/spring/docs/1.2.x/reference/mvc.html
java.sun.com/javaee/javaserverfaces
References