Struts2

44

description

Struts2 by Ori Day from AlphaCSPwww.alphacsp.com

Transcript of Struts2

Page 1: Struts2
Page 2: Struts2

2Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar

Struts2 Struts2 Reinventing Struts1 WheelReinventing Struts1 Wheel

Ori DarConsultant and Architect,

AlphaCSP

Page 3: Struts2

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

Page 4: Struts2

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

Page 5: Struts2

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

Page 6: Struts2

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

Page 7: Struts2

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

Page 8: Struts2

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

Page 9: Struts2

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

Page 10: Struts2

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

Page 11: Struts2

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

Page 12: Struts2

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

Page 13: Struts2

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

Page 14: Struts2

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

Page 15: Struts2

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

Page 16: Struts2

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

Page 17: Struts2

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

Page 18: Struts2

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

Page 19: Struts2

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

Page 20: Struts2

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

Page 21: Struts2

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

Page 22: Struts2

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…

Page 23: Struts2

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

Page 24: Struts2

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

Page 25: Struts2

25Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar

FeaturesFeatures::Page flow::Page flow

1

3

4

5

6

7

8

2

Page 26: Struts2

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

Page 27: Struts2

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

Page 28: Struts2

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

Page 29: Struts2

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

Page 30: Struts2

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

Page 31: Struts2

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)

Page 32: Struts2

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

Page 33: Struts2

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

Page 34: Struts2

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

Page 35: Struts2

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

Page 36: Struts2

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

Page 37: Struts2

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

Page 38: Struts2

39Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar

FeaturesFeatures::Documentation::Documentation

•Apache Struts 2 Documentation•WIKI •Struts Showcase•Plugins

Page 39: Struts2

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

Page 40: Struts2

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

Page 41: Struts2

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

Page 42: Struts2

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

Page 43: Struts2

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

Page 44: Struts2

45Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar

Thank Thank You !You !