You are on page 1of 45

Struts2

Reinventing Struts1 Wheel

Ori Dar
Consultant and Architect,
AlphaCSP

2
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Agenda

 Introduction
 Background
 Framework features review
 Configuration
 View technology
 Page flow
 Form binding
 Table sorting
 Pagination
 Validation
 AJAX
 Error handling
 I18n support
 Documentation
 Summary

3
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::In a nutshell (1)

• Action Based MVC Framework


–FilterDispatcher : controller
–Action : POJO model
–Result : view
• Comparable to
–Struts1
–Spring MVC
–Stripes
4
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
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

5
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
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

6
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::HelloWorld

Controller: FilterDispatcher

<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>
web.xml

7
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::HelloWorld, Model

We don’t have public class HelloWorld {


to extend Action
Boss private String message="Hello World. Time is: ";

public String execute() {


message += new Date();
return "success";
}

public String getMessage() {


return message;
}
}

… and no request, action method


response in execute() returns
Boss a result code

8
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::HelloWorld, View

View: HelloWorld.jsp
–Utilizes a single struts taglib
–The taglib is common for JSP, Velocity
and FreeMarker

Prints action’s
<%@ taglib prefix="s" uri="/struts-tags"%>
message property.
<html>
<body>
Unlike struts1,
<s:property value=“message“/> action is a POJO,
</body> and acts as a model
</html>

9
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Introduction::HelloWorld

struts.xml:
–Actions mapping links action to view

–Results mapping
<action name=“hello“ class="com.alphacsp.actions.HelloWorld">
<result name=“success“>/pages/HelloWorld.jsp</result>
</action>

Use action name in URL invocation


http://host:port/app/hello.action

10
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Agenda

 Introduction
 Background
 Framework features review
 Configuration
 View technology
 Page flow
 Form binding
 Table sorting
 Pagination
 Validation
 AJAX
 Error handling
 I18n support
 Documentation
 Summary

11
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Background::S2 Vs. S1

Struts2 Struts1
POJO (with execute) Action Extends Action
Model Action Role Controller
Decoupled Servlet API Dependant
Instance per request Threading Single instance
Action JavaBean Form binding Action Form
properties
Value Stack View binding JSP mechanisms
OGNL EL JSTL EL
xml or annotations Validation Action Form
Independent via Lifecycle Shared
interceptors
Wildcards, annotations Configuration Verbose

12
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Background::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.xml

13
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Background::Interceptors

Excerpt from struts-default.xml


<package name="struts-default" abstract="true">
interceptor
<interceptors>
<interceptor name="params" class="…"/>

<interceptor-stack name="basicStack">
<interceptor-ref name="exception"/> interceptor stack
<interceptor-ref name="servletConfig"/> contains other interceptors
<interceptor-ref name="prepare"/>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError"/>
</interceptor-stack> the default stack
</interceptors> for actions in package

<default-interceptor-ref name="defaultStack"/>
</package> struts-default.xml

14
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Background::ValueStack

• 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

15
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Background::OGNL

•ValueStack is referenced and


manipulated by OGNL
•OGNL is also used instead of JSTL
<s:textfield name="contact.email"/> phoneBook.jsp

retrieves email property retrieves localized message


of actions’ contact property using email as key
from stack using OGNL from stack using OGNL

<s:text name="email"/> phoneBook.jsp


16
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Background::Other 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

17
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Background:: 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>
login.jsp

Xhtml theme generates


table and validation feedback.
No themes in Struts1

18
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Background::Other 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

19
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Agenda

 Introduction
 Background
 Framework features review
 Configuration
 View technology
 Page flow
 Form binding
 Table sorting
 Pagination
 Validation
 AJAX
 Error handling
 I18n support
 Documentation
 Summary

20
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Action Configuration

action name action method


matched by a URL within action class
(default value: “execute”)
action class

<action name="listEmployees" class="actions.model.Employee" method="list">


<result name="list" type="dispatcher">/WEB-INF/list.jsp</result>
</action>

result name
result type
action method should return
the view technology
a matching result code string
(default value: “dispatcher”
(default value: “success”)
for rendering JSP)

21
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features:: Action Configuration

•Wildcards can be used for mapping


•Mandates naming convention
•Makes XML much less verbose
listEmployees.action is mapped to Employee class and listEmployees.jsp
listDepartments.action is mapped to Department class and listDepartmrnts.jsp

<action name="list*s" class="actions.model.{1}" method="list">


<result name="list">/WEB-INF/list{1}s.jsp</result>
</action>

22
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Annotation Config.

•Annotation based configuration


–Can make XML utterly redundant
–Struts scans packages for action classes
–Results are expressed via @Result
@Result(name="list", value="/WEB-INF/list.jsp") “list” result code
public class Employee extends ActionSupport is mapped to JSP.
{
public String listEmployees() { By extending ActionSupport,
// business logic goes here Employee is mapped
return "list"; as action by the
} package scanning
} mechanism
23
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::View technology

• Result types
– JSP : dispatcher
– Velocity
– FreeMarker
– XSLT
– Stream : PDF, MS Word etc.
• Plugins
– JasperReports
– JFreeChart
– JSON

24
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Page flow

2
4

3
5

25
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Page flow

• User Sends HTTP request


• FilterDispatcher determines appropriate
action
• Interceptors are applied
• Action parameters are set (via params
interceptor)
• Action is being executed
• The Result (view) renders the output
• Optionaly: the view retrieves data from
action
• The result is displayed to the user
26
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Form 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.jsp

Form field parameters


are injected into setter
methods by the params
public class Login { interceptor

private String username;

public void setUsername(String username) {


this.username = username;
}
}
Login.java

27
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::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
28
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Table sorting

From demo application

<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> phoneBook.jsp

29
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Pagination

Used the display tag library internal


pagination support
– Supports internal and external
pagination
– Forces you to use HTTP GET
– Adds pagination parameter to request

30
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::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

31
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Validation

Annotation vs. xml example


(No annotated version for Struts1)

<validators>
@EmailValidator(
<field name="email">
fieldName = "email",
<field-validator type="email">
key="wrongEmailFormat",
<message key="wrongEmailFormat">
message="Wrong Email Format")
Wrong Email Format
</message>
public void setEmail(String email) {
</field-validator>
this.email = email;
</field>
}
</validators>
PhoneBook.java PhoneBook_validation.xml

32
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Client side validation

•Automatic creation of client side


validation
–No client side for expression validators
–Apply a theme for generating error
feedback markup
<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>
login.jsp

33
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::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

34
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Ajax autocompleter

View
<s:url id="acUrl" action="getDepts"/>
<s:autocompleter name="dept" href="%{acUrl}" cssClass="acSearchField"/>

phoneBook.jsp
Action
privateList<String> ;deptList
action name=""getDepts>
public String execute() {
<class=""DeptsAutoComplete
deptList = service.findAllDepartments();
<result type=""json>
return ActionSupport.SUCCESS;
<param name="root">deptList</param>
}
<result/>
<action/>
public List<String> getDeptList() {
return deptList;
} PhoneBook.java struts-default.xml

35
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Error handling

• Validation error feedback tags


– actionerror
– actionmessage
– fielderror: per form field
• Two framework supporting interfaces
– Validatable: for programmatic validation
– ValidationAware: for UI feedback

36
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Error handling

•Exception interceptor
–maps exceptions to result error pages
–should be first in interceptor stack

<!-- 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>
struts.xml

37
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::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

38
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Features::Documentation

•Apache Struts 2 Documentation


•WIKI
•Struts Showcase
•Plugins

39
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Agenda

 Introduction
 Background
 Framework features review
 Configuration
 View technology
 Page flow
 Form binding
 Table sorting
 Pagination
 Validation
 AJAX
 Error handling
 I18n support
 Documentation
 Summary

40
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Summary::Pros

Extensible plugin framework


Modular and clean architecture
Annotation or xml configuration
Customized lifecycle via interceptors
Neat form & view binding
Easy client side validation
Markup generation with themes

41
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Summary::Pros

Fast learning curve


Intuitive
Restful URL action mapper
Easy to test (POJOs) using plugins
DI via lightweight containers
Decoration with tiles, sitemash

42
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Summary::Cons

Unorganized documentation
Lack of API documentation
No clear roadmap
ActionSupport dependency
Lack of @Action
Lack of @Interceptor
Cases when fallback to Servlet API is
needed
Weakly typed sessions

43
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Summary::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

44
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
Thank
You !
45
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar

You might also like