Struts2
description
Transcript of Struts2
2Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Struts2 Struts2 Reinventing Struts1 WheelReinventing Struts1 Wheel
Ori DarConsultant and Architect,
AlphaCSP
3Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
AgendaAgenda
Introduction Background Framework features review
Configuration View technology Page flow Form binding Table sorting Pagination Validation AJAX Error handling I18n support Documentation
Summary
4Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::In a nutshell (1)Introduction::In a nutshell (1)
• Action Based MVC Framework– FilterDispatcher : controller– Action : POJO model– Result : view
• Comparable to – Struts1– Spring MVC– Stripes
5Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::In a nutshell (2)Introduction::In a nutshell (2)
•First released in Oct. 2006–Merger of Struts1 and WebWork2–Uses WebWork2 architecture
•Modern and clean architecture•Xml or annotations
–Actions–Validators–Datatype convertors
6Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::In a nutshell (3)Introduction::In a nutshell (3)
•Extensible via plugins–Other frameworks integration–Embedding other application modules
•Intuitive, fast learning curve•Other core components
–Interceptors: controlling action pre and post processing–ValueStack: central storage for request model data
7Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::HelloWorldIntroduction::HelloWorld
<filter> <filter-name>action2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter>
<filter-mapping> <filter-name>action2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Controller: FilterDispatcher
web.xmlweb.xml
8Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::HelloWorld, ModelIntroduction::HelloWorld, Model
public class HelloWorld {
private String message="Hello World. Time is: ";
public String execute() { message += new Date();
return "success"; }
public String getMessage() { return message; }}
action methodreturns
a result code
We don’t have to extend Action
Boss
We don’t have to extend Action
Boss
… and no request, response in execute()
Boss
… and no request, response in execute()
Boss
9Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::HelloWorld, ViewIntroduction::HelloWorld, View
<%@ taglib prefix="s" uri="/struts-tags"%><html> <body>
<s:property value=“message“/> </body></html>
View: HelloWorld.jsp–Utilizes a single struts taglib–The taglib is common for JSP, Velocity and FreeMarker
Prints action’s message property.
Unlike struts1, action is a POJO,
and acts as a model
10Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::HelloWorldIntroduction::HelloWorld
<action name=“hello“ class="com.alphacsp.actions.HelloWorld">
<result name=“success“>/pages/HelloWorld.jsp</result> </action>
struts.xml:–Actions mapping–Results mapping
links action to view
http://host:port/app/hello.action
Use action name in URL invocation
11Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
AgendaAgenda
Introduction Background Framework features review
Configuration View technology Page flow Form binding Table sorting Pagination Validation AJAX Error handling I18n support Documentation
Summary
12Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
BackgroundBackground::S2 Vs. S1::S2 Vs. S1
Struts2Struts1POJO (with execute)ActionExtends Action
ModelAction RoleController
DecoupledServlet APIDependant
Instance per requestThreadingSingle instance
Action JavaBean properties
Form bindingAction Form
Value StackView bindingJSP mechanisms
OGNLELJSTL EL
xml or annotationsValidationAction Form
Independent via interceptors
LifecycleShared
Wildcards, annotationsConfigurationVerbose
13Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
BackgroundBackground::Interceptors::Interceptors
• Actions pre & post processing mechanism
• Like Spring AOP, EJB3 interceptors• Interceptors are packed in stacks• Custom interceptors and stacks can
be added• No equivalent in Struts1
<action name="phoneBook" class="com.alphacsp.actions.PhoneBook">
<interceptor-ref name="acspStack"/> <result>/pages/phoneBook.jsp</result></action> struts.xmlstruts.xml
14Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
BackgroundBackground::Interceptors::Interceptors
<package name="struts-default" abstract="true">
<interceptors> <interceptor name="params" class="…"/>
<interceptor-stack name="basicStack"> <interceptor-ref name="exception"/> <interceptor-ref name="servletConfig"/> <interceptor-ref name="prepare"/> <interceptor-ref name="checkbox"/> <interceptor-ref name="params"/> <interceptor-ref name="conversionError"/> </interceptor-stack> </interceptors>
<default-interceptor-ref name="defaultStack"/></package>
Excerpt from struts-default.xml
interceptor
interceptor stackcontains other interceptors
the default stackfor actions in package
struts-default.xmlstruts-default.xml
15Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
BackgroundBackground::V::ValueStack alueStack
• The ValueStack is a storage for request domain model
• Serves as context per request • “Glues” model and view• Accessed by interceptors & views• Stores action properties• Also stores message bundles
16Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
BackgroundBackground::OGNL::OGNL
•ValueStack is referenced and manipulated by OGNL •OGNL is also used instead of JSTL<s:textfield name="contact.email"/>
<s:text name="email"/>
phoneBook.jspphoneBook.jsp
phoneBook.jspphoneBook.jsp
retrieves email propertyof actions’ contact property
from stack using OGNL
retrieves localized messageusing email as key
from stack using OGNL
17Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
BackgroundBackground::::Other featuresOther features
• Tag Library– Form component tags– Ajax UI component tags– Control tags: iterator, if/else… – Data tags: manipulate the ValueStack
• Datatype conversion framework• Themes: templates for customizing
components markup
18Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
BackgroundBackground:::: Theme example Theme example
<s:form action="login" namespace="/" validate="true"> <s:textfield cssClass="loginField" size="25" key="username"/> <s:password cssClass="loginField" size="25" key="password"/> <s:submit value="Login" cssClass="button" align="center"/></s:form>
Xhtml theme generates table and validation feedback.
No themes in Struts1
login.jsplogin.jsp
19Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
BackgroundBackground::::Other featuresOther features
• Reasonable defaults: struts-default– Result types– Interceptor stacks
• Actions extending ActionSupport– facilitates validation– facilitates localization
• Spring integration– Dependency Injection interceptor– Full Spring lifecycle management
20Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
AgendaAgenda
Introduction Background Framework features review
Configuration View technology Page flow Form binding Table sorting Pagination Validation AJAX Error handling I18n support Documentation
Summary
21Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Action Configuration::Action Configuration
<action name="listEmployees" class="actions.model.Employee" method="list"><result name="list" type="dispatcher">/WEB-INF/list.jsp</result>
</action>
result typethe view technology
(default value: “dispatcher”for rendering JSP)
result nameaction method should returna matching result code string
(default value: “success”)
action methodwithin action class
(default value: “execute”)action class
action name matched by a URL
22Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures:: Action Configuration:: Action Configuration
<action name="list*s" class="actions.model.{1}" method="list">
<result name="list">/WEB-INF/list{1}s.jsp</result></action>
•Wildcards can be used for mapping•Mandates naming convention•Makes XML much less verbose
listEmployees.action is mapped to Employee class and listEmployees.jsplistDepartments.action is mapped to Department class and listDepartmrnts.jsp…
23Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Annotation Config.::Annotation Config.
@Result(name="list", value="/WEB-INF/list.jsp")public class Employee extends ActionSupport{ public String listEmployees() { // business logic goes here
return "list"; }}
•Annotation based configuration –Can make XML utterly redundant–Struts scans packages for action classes–Results are expressed via @Result
“list” result codeis mapped to JSP.
By extending ActionSupport,Employee is mapped
as action by the package scanning
mechanism
24Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::::View technologyView technology
• Result types– JSP : dispatcher– Velocity– FreeMarker– XSLT– Stream : PDF, MS Word etc.
• Plugins– JasperReports– JFreeChart– JSON
25Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Page flow::Page flow
1
3
4
5
6
7
8
2
27Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::::Form bindingForm binding
<s:form action="login" validate="true" namespace="/">
<s:textfield cssClass="loginField" key="username"/>
<s:submit key="login" cssClass="button" align="center"/>
</s:form>login.jsplogin.jsp
public class Login {
private String username;
public void setUsername(String username) {this.username = username;
}}
Login.javaLogin.java
Form field parameters are injected into setter
methods by the params interceptor
28Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Table sorting::Table sorting
1. Using Table Tags plugin– Undocumented– Looks inactive– Lack of evidence
2. Using Dojo + JSON – Too complex
3. YUI DataTable – Buggy, beta
4. Display tag library
29Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Table sorting::Table sorting
<display:table class="grid" defaultsort="1" id=“contact" name=“contacts" pagesize="5" requestURI="phoneBook.acsp" sort="list">
<display:column class="grid" escapeXml="true" headerClass="grid" property="fullName" title="Name" sortable="true" defaultorder="ascending"/>
<display:column class="grid" escapeXml="false" headerClass="grid" title="Email" style="border-left: 1px solid #5680AA;">
<s:textfield value="%{#attr.contact.email}" theme="simple"/>
</display:column></display:table>
From demo application
phoneBook.jspphoneBook.jsp
30Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::::PaginationPagination
Used the display tag library internal pagination support– Supports internal and external
pagination– Forces you to use HTTP GET– Adds pagination parameter to request
31Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Validation::Validation
• Uses 12 out-of-box field validators• Uses expression validators for
complex validations• Validators can be declared using xml• Validators can be declared using
annotations– Field validators for setter methods– Expression validator for action methods
32Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Validation::Validation
@EmailValidator(fieldName = "email", key="wrongEmailFormat", message="Wrong Email Format")
public void setEmail(String email) { this.email = email;}
PhoneBook.javaPhoneBook.java
<validators><field name="email"> <field-validator type="email"> <message key="wrongEmailFormat">
Wrong Email Format </message> </field-validator> </field></validators> PhoneBook_validation.xmlPhoneBook_validation.xml
Annotation vs. xml example(No annotated version for Struts1)
33Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Client side validation::Client side validation
<s:actionerror cssClass="feedback"/>
<s:form action="login" namespace="/" validate="true" > <s:textfield cssClass="loginField" size="25" key="username"/> <s:password cssClass="loginField" size="25" key="password"/> <s:submit value="Login" cssClass="button" align="center"/></s:form>
•Automatic creation of client side validation
–No client side for expression validators–Apply a theme for generating error feedback markup
login.jsplogin.jsp
34Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Ajax::Ajax
• Dojo is embedded for Ajax tags• Dojo head tag enables JS debugging• Ajax requests are handled by actions• DWR integration is enabled via plugin• YUI integration is enabled via plugin• Ajax file upload via plugin• Ajax behaviour for component tags
35Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::::Ajax autocompleterAjax autocompleter
View
Action
<s:url id="acUrl" action="getDepts"/>
<s:autocompleter name="dept" href="%{acUrl}" cssClass="acSearchField"/>
private List<String> deptList;
public String execute() { deptList = service.findAllDepartments(); return ActionSupport.SUCCESS;}
public List<String> getDeptList() { return deptList; }
phoneBook.jspphoneBook.jsp
PhoneBook.javaPhoneBook.java
>action name="getDepts" class="DeptsAutoComplete" <
>result type="json" <>param name="root">deptList</param <
/>result </>action <
struts-default.xmlstruts-default.xml
36Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Error handling::Error handling
• Validation error feedback tags– actionerror– actionmessage– fielderror: per form field
• Two framework supporting interfaces– Validatable: for programmatic validation– ValidationAware: for UI feedback
37Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Error handling::Error handling
<!-- Fallback error page: --> <global-results> <result name="sysError">/pages/systemError.jsp</result> </global-results>
<global-exception-mappings> <exception-mapping exception="java.lang.Exception" result="sysError"/> </global-exception-mappings>
•Exception interceptor–maps exceptions to result error pages–should be first in interceptor stack
struts.xmlstruts.xml
38Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::I18N support::I18N support
• Built on top of Java I18N support• Bundles can be defined in:
– action.properties – package.properties– global resource properties
• Bundles pushed to ValueStack• Validation errors can be localized• Locale interceptor to switch locale
39Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
FeaturesFeatures::Documentation::Documentation
•Apache Struts 2 Documentation•WIKI •Struts Showcase•Plugins
40Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
AgendaAgenda
Introduction Background Framework features review
Configuration View technology Page flow Form binding Table sorting Pagination Validation AJAX Error handling I18n support Documentation
Summary
41Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Summary::ProsSummary::Pros
Extensible plugin frameworkModular and clean architecture Annotation or xml configurationCustomized lifecycle via interceptorsNeat form & view binding Easy client side validationMarkup generation with themes
42Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Summary::ProsSummary::Pros
Fast learning curveIntuitiveRestful URL action mapperEasy to test (POJOs) using pluginsDI via lightweight containersDecoration with tiles, sitemash
43Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Summary::ConsSummary::Cons
Unorganized documentationLack of API documentationNo clear roadmapActionSupport dependencyLack of @ActionLack of @InterceptorCases when fallback to Servlet API is needed Weakly typed sessions
44Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Summary::When to useSummary::When to use
• Use when– Migrating from legacy framework– Natural around HTTP request response
paradigm– Suitable for streaming– POC, prototype, RAD
• Don’t use when– Heavily utilized RIA is needed– Your developers have Swing orientation
45Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Thank Thank You !You !