Practical Java EE 5 Presentation Layer Technologies

Download Report

Transcript Practical Java EE 5 Presentation Layer Technologies

Struts 2.0 - Overview

Module 1_A: Struts Framework Copyright © 2010 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Module Objectives

• At the end of this module, participants will be able to: – Struts 1.2 Framework revision – Introduction to Struts 2 architecture – Sample example on Struts 2.0

– Struts 2 features – Struts 1 vs. Struts 2 Copyright © 2010 Accenture All Rights Reserved. 2

Struts 1.2 Framework revision

• Open source framework for Java based web applications • Based on MVC • Struts 1 – JSP views – Action classes – Form beans – Struts-config.xml

• Action mappings • Form beans mappings – Validation • Validation-rules • Automatic • Manual Copyright © 2010 Accenture All Rights Reserved. 3 4/26/2020

Basic Struts Architecture

Client

•Request •Response • Server •Struts Framework •Control •Server •Model •View • Database Copyright © 2010 Accenture All Rights Reserved.

Struts 1 Flow

Copyright © 2010 Accenture All Rights Reserved.

Struts 1 Flow

Copyright © 2010 Accenture All Rights Reserved.

Agenda

• Struts 1.2 Framework revision • Introduction to Struts 2 • Struts 2 architecture • Sample example on Struts 2.0

• Struts 2 features • Struts 1 vs. Struts 2 Copyright © 2010 Accenture All Rights Reserved. 7

Introduction to Struts 2.0

• Combination of Apache struts and OpenSymphony WebWork • Action Based Framework • Create web application using MVC 2 architecture • Apache Struts offer two major version • Struts 1.x

• Struts 2.0

• Struts 2 = WebWork + Struts Copyright © 2010 Accenture All Rights Reserved. 8 4/26/2020

Struts 2 Components

Copyright © 2010 Accenture All Rights Reserved.

Agenda

• Struts 1.2 Framework revision • • Introduction to Struts 2 Struts 2 features • Struts 2 architecture • Sample example on Struts 2.0

• Struts 1 vs. Struts 2 Copyright © 2010 Accenture All Rights Reserved. 10

Struts 2.0 features

POJO forms and POJO actions

POJO as an Action class.

- Struts2 has done away with the Action Forms that were an integral part of the Struts framework. With Struts2, you can use any POJO to receive the form input. Similarly, you can now see any •

Tag support

- Struts2 has improved the form tags and the new tags allow the developers to write less code.

AJAX support

- Struts2 has recognised the take over by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, that function very similar to the standard Struts2 tags.

Easy Integration

- Integration with other frameworks like Spring, Tiles and SiteMesh is now easier with a variety of integration available with Struts2.

Template Support

- Support for generating views using templates.

Copyright © 2010 Accenture All Rights Reserved.

11

Struts 2.0 features

Plugin Support

augmented by the use of plugins. A number of plugins are available for Struts2.

- The core Struts2 behavior can be enhanced and •

Profiling

- Struts2 offers integrated profiling to debug and profile the application. In addition to this, Struts also offers integrated debugging with the help of built in debugging tools.

Easy to modify tags

- Tag markups in Struts2 can be tweaked using Freemarker templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS knowledge is enough to modify the tags.

Promote less configuration

- Struts2 promotes less configuration with the help of using default values for various settings. You don't have to configure something unless it deviates from the default settings set by Struts2.

View Technologies:

- Struts2 has a great support for multiple view options (JSP, Freemarker, Velocity and XSLT) Copyright © 2010 Accenture All Rights Reserved.

12

Agenda

• Struts 1.2 Framework revision • Introduction to Struts 2 • Struts 2 features • Struts 2 architecture • Sample example on Struts 2.0

• Struts 1 vs. Struts 2 Copyright © 2010 Accenture All Rights Reserved. 13

Struts 2.0 Components

Interceptors

Value Stack

ActionContext

ActionInvocation

OGNL

Copyright © 2010 Accenture All Rights Reserved.

14

Struts 2.0 Components

Interceptors

:-

– Can execute code before and after an Action is executed.

– They can be configured per action basis.

– Can be used to perform data validation, file upload, exception handling and internationalization in Struts 2.0.

Value Stack:-

– It is a stack that contains application specific objects such as action objects and other model object – At execution time action is placed on the top of the stack – It is possible to put objects in stack, query it and delete them.

Copyright © 2010 Accenture All Rights Reserved.

15

Struts 2.0 Components

ActionContext

: – Is container of objects in which action is executed.

– The values stored in ActionContext are unique per thread.

ActionInvocation:-

– Represents the execution state of an action.

– It holds action and interceptors objects.

ONGL (Object Graph Navigation Language) :-

- Is an expression language.

- It simplifies the accessibility of data stored in ActionContext - The struts framework sets the ValueStack as the root object of ONGL.

Action

: – It is a POJO class and will have only

execute

the business logic. method that represents Copyright © 2010 Accenture All Rights Reserved.

16

Struts 2.0 Basic Flow

Copyright © 2010 Accenture All Rights Reserved.

17

Struts 2.0 Basic Flow

1.

2.

3.

4.

5.

6.

7.

User Sends Request Filter Dispatcher determines the appropriate action Interceptors are applied Execution of action Output Rendering Return of Request Display of result to user.

Copyright © 2010 Accenture All Rights Reserved.

18

Struts 2.0 Basic Flow

Copyright © 2010 Accenture All Rights Reserved.

19

Struts 2.0 Complete Flow

1. User sends a request for the action 2. Container maps the request in the web.xml file and gets the class name of controller.

3. Container invokes the controller (StrutsPrepareAndExecuteFilter or FilterDispatcher). Since struts2.1, it is StrutsPrepareAndExecuteFilter. Before 2.1 it was FilterDispatcher.

4. Controller gets the information for the action from the ActionMapper 5. Controller invokes the ActionProxy 6. ActionProxy gets the information of action and interceptor stack from the configuration manager which gets the information from the struts.xml file.

Copyright © 2010 Accenture All Rights Reserved.

20

Struts 2.0 Complete Flow

7.

ActionProxy forwards the request to the ActionInvocation 8.

ActionInvocation invokes each interceptors and action 9.

A result is generated 10. The result is sent back to the ActionInvocation 11. HttpServletResponse is generated 12. Response is sent to the user Copyright © 2010 Accenture All Rights Reserved.

21

Struts 2.0 Architecture

Copyright © 2010 Accenture All Rights Reserved.

22

Struts 2 Lifecycle

Copyright © 2010 Accenture All Rights Reserved.

Struts 2 – Behind the scenes

Copyright © 2010 Accenture All Rights Reserved. 24 4/26/2020

Agenda

• Struts 1.2 Framework revision • Introduction to Struts 2 • Struts 2 architecture • Sample example on Struts 2.0

• Struts 2 features • Struts 1 vs. Struts 2 Copyright © 2010 Accenture All Rights Reserved. 25

Example on Struts 2

• Hello World!!!

Copyright © 2010 Accenture All Rights Reserved. 26 4/26/2020

Hello World!

• One time configuration – Web.xml

• Three steps process – Create view (JSP) – Create Action Class – Map Action and view Copyright © 2010 Accenture All Rights Reserved. 27 4/26/2020

Web.xml

• Placed in WEB-INF folder Struts Example defaultDispatcher org.apache.struts2.dispatcher.FilterDispatcher

defaultDispatcher /* 28 4/26/2020 Copyright © 2010 Accenture All Rights Reserved.

Welcome.jsp

• Creating Welcome Page <%@ page contentType = "text/html; charset=UTF-8" %>

<%@ taglib prefix = "

s

" uri = "/struts-tags" %>

< html > < head > < title > Welcome < body >

< s :property value = "message" />

Copyright © 2010 Accenture All Rights Reserved. 29 4/26/2020

Welcome.java

} package

import example

;

com.opensymphony.xwork2.ActionSupport

; public class

Welcome

extends

ActionSupport

{

private String message = "default String" ;

} public String

getMessage

() { return message ; } public void

setMessage

(String message) { this .

message = message; public String

execute()

throws Exception {

message = “Hello World! My First App is running" ;

return

SUCCESS

; // String SUCCESS = “success” } • Creating Welcome Page Copyright © 2010 Accenture All Rights Reserved. 30 4/26/2020

Welcome.java

• Either implement ActionSupport • Or extend Action • Or neither – Do provide execute method – Framework will search for execute method through Reflection • Default execute method returns SUCCESS • Execute is the default entry point for Action class • Some return strings constants are already provided – SUCCESS=“success” – INPUT=“input” – NONE=“none” – ERROR=“error” – LOGIN=“login” • SUCCESS is the default return string – Also returned by default execute method Copyright © 2010 Accenture All Rights Reserved. 31 4/26/2020

Struts.xml

• Creating Welcome Page

xml version = "1.0" encoding = "UTF-8" ?>

DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" > < struts > < constant name = "struts.enable.DynamicMethodInvocation" value = “false" /> < constant name = "struts.devMode" value = "false" />

< package name = "StrutsExample" extends = "struts-default" > < action name = " Welcome " class = "example.Welcome" > < result > /jsp/welcome.jsp

Copyright © 2010 Accenture All Rights Reserved. 32 4/26/2020

• Welcome Page •url= http://localhost:8081/struts2/ Welcome.action

• welcome.jsp

< s :property value = "message" />

< action name = " Welcome "

class = "example.Welcome" >

• Welcome.java

private

• •

public String message = "default String" ; String getMessage() {

}

• • •

return public void message ; setMessage (String message) {

this .

message = message;

}

Copyright © 2010 Accenture All Rights Reserved. 33 4/26/2020

Module Objectives

• At the end of this module, participants will be able to: – Struts 1.2 Framework revision – Introduction to Struts 2 architecture – Sample example on Struts 2.0

– Struts 2 features – Struts 1 vs. Struts 2 Copyright © 2010 Accenture All Rights Reserved. 34

Struts 1.x vs Struts 2.0

Feature Struts 1 Struts 2 Action classes

Struts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces.

Any POJO object with a execute signature can be used as an Struts 2 Action object.

Threading Model

Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues

Servlet Dependency

Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked.

Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required.

Copyright © 2010 Accenture All Rights Reserved.

Struts 1.x vs Struts 2.0

Testability Expression Language Validation

A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1.

Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.

Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.

Struts 2 can use JSTL.

The framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects.

Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

Copyright © 2010 Accenture All Rights Reserved.

Struts 1.x vs Struts 2.0

Binding values into views

Struts 1 uses the standard JSP mechanism Struts 2 uses a "ValueStack" technology so that the for binding objects into the page context for access.

taglibs can access values without coupling your view to the object type it is rendering.

Type Conversion Control Of Action Execution

The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.

Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons Beanutils for type conversion. Converters are per-class, and not configurable per instance.

Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle.

Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.

Copyright © 2010 Accenture All Rights Reserved.

Struts 1 vs. Struts 2

Copyright © 2010 Accenture All Rights Reserved. 38 4/26/2020

Interceptors

• Interceptors are responsible for common tasks like Validation, Session Control, Authentication, File Upload, Logging.

• They are invoked by the controller before and after invoking action, thus they sits between the controller and action.

• They can be configured on a per action basis.

• They are defined in a stack that specifies the execution order.

Copyright © 2010 Accenture All Rights Reserved.

Interceptor Flow

Copyright © 2010 Accenture All Rights Reserved. 40

Interceptor in Action Life-cycle

Copyright © 2010 Accenture All Rights Reserved.

File Upload Interceptor

• The

fileUpload

interceptor automatically works for all the requests that includes files. • We can use this interceptor to control the working of file upload in struts2 such as defining allowed types, maximum file size etc.

• It automatically adds 3 parameters in the request: – – –

File file

represents the file. We can apply methods on this object.

String fileName

represents the filename of the file.

String contentType

specifies the content type of the file.

Copyright © 2010 Accenture All Rights Reserved.

Custom Interceptors

To create own interceptor the class should implement Interceptor interface and override following methods.

– init() – intercept (ActionInvocation invocation) – destroy() Copyright © 2010 Accenture All Rights Reserved.

Custom Interceptor

• For creating the custom interceptor,

Interceptor

interface must be implemented. It has three methods:

public void init()

– It is invoked only once and used to initialize the interceptor.

public void intercept(ActionInvocation ai)

– It is invoked at each request, it is used to define the request processing logic. If it returns string, result page will be invoked, if it returns invoke() method of ActionInvocation interface, next interceptor or action will be invoked.

public void destroy()

It is invoked only once and used to destroy the interceptor.

Copyright © 2010 Accenture All Rights Reserved.

Struts 2.0 Validation

• There are three ways to perform validation in struts 2.

By Custom Validation

: Implement the Validateable interface (or extend ActionSupport class) and provide the implementation of validate method.

By Input Validation (built-in validators)

: Struts 2 provides a lot of predefined validators that can be used in struts 2 application. Copyright © 2010 Accenture All Rights Reserved.

Struts 2.0 Validation

Struts 2 provides following bundled validators.

• requiredstring validator • stringlength validator • email validator • date validator • int validator • double validator • url validator • regex validator •

By Ajax Validation (built-in validators with ajax) :-

we can use jsonValidation interceptor to perform validation with ajax.

Copyright © 2010 Accenture All Rights Reserved.

Custom Validation

• We can define our own validation logic (custom validation) in struts 2 by implementing the

Validateable

interface in the action class.

• The

workflow interceptor

is used to get information about the error messages defined in the action class.

• The

workflow interceptor

checks if there is any validation errors or not. It doen't perform any validation. • It is applied when action class implements the Validateable interface. The

input

is the default parameter for this interceptor that determines the result to be invoked for the action or field error.

• It is found in the defaultStack so we don't need to define it explicitly.

Copyright © 2010 Accenture All Rights Reserved.

Custom Validation

Validateable interface

- The

Validateable

interface must be implemented to perform validation logic in the action class. - It contains only one method v

alidate()

that must be overridden in the action class to define the validation logic. •

ValidationAware interface

- The

ValidationAware

interface can accept the

field level level

error messages. or

action class

- The field level messages are kept in Map and Action class level messages are kept in collection. - It should be implemented by the action class to add any error message.

Copyright © 2010 Accenture All Rights Reserved.

ValueStack

• Consists of following objects in the provided order: • Temporary Objects

– during execution temporary objects

are created and placed onto the value stack. example -> current iteration value for a collection being looped over in JSP tag.

• Model Object action on VS

current model object is placed before the Copyright © 2010 Accenture All Rights Reserved.

ValueStack

• Action Object

– action being executed

• Named Objects

– objects are application, session, request, attr and parameters

Objects are examined to find property values.

• The value stack can be accessed via the tags provided for JSP, Velocity or Freemarker.

Copyright © 2010 Accenture All Rights Reserved.

ValueStack

Copyright © 2010 Accenture All Rights Reserved.

How is ValueStack used

• Action instance is pushed on ValueStack • Model pushed by ModelDrivenInterceptor • The UI tags to push values during their scope and evaluate expressions Copyright © 2010 Accenture All Rights Reserved.

s:iterator s:bean s:property

How is ValueStack used

pushes the current item pushes a bean instance evaluates an expression against the stack Copyright © 2010 Accenture All Rights Reserved.

OGNL Expression Language

• An expression and binding language for getting and setting properties of Java objects.

• Same expression is used for getter and setter properties.

• Independent Open Source project.

Copyright © 2010 Accenture All Rights Reserved.

OGNL Expression Language

The Object-Graph Navigation Language

(OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. • OGNL also helps in data transfer and type conversion.

• The OGNL is very similar to the JSP Expression Language. • OGNL is based on the idea of having a root or default object within the context. The properties of the default or root object can be referenced using the markup notation, which is the pound symbol.

Copyright © 2010 Accenture All Rights Reserved.

OGNL Expression Language

• OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContext map consists of the following: • • • • • •

application

- application scoped variables

session

- session scoped variables

root / value stack

- all your action variables are stored here

request

- request scoped variables

parameters

- request parameters

atributes

- the attributes stored in page, request, session and application scope Copyright © 2010 Accenture All Rights Reserved.

OGNL Examples OGNL

user.name user.toString() item.categories[0] @com.example.Test@foo() name in {null,”fred”} categories.{name}

Result

getUser().getName() getUser().toString() First element of Categoriescollection Calls the static foo() method on the com.example.Test class True if name is null or “fred” Calls getName() on each Category in the collection, returning a newcollection (projection) Copyright © 2010 Accenture All Rights Reserved.

View

● It is reusable user interface tags allow UI development using themes and templates.

● It has bundled tags ● OGNL exposes properties on multiple objects like single JavaBean.

● It supports multiple view technologies including JSP, FreeMarker, Velocity.

Copyright © 2010 Accenture All Rights Reserved.

Themes

simple the tag output without formatting xhtml this theme provides two column formatting using HTML tables css_xhtml formatting using CSS DIV Copyright © 2010 Accenture All Rights Reserved.

Struts 2 with i18n Interceptor

• The

i18n

interceptor provides multi-lingual support for application.

• It handles setting locale for the action. • It can be used if user wants to set his/her locale and get data according to the locale provided.

• Following are parameters for i18n Interceptor

Parameter parameterName Description It specifies the name of the HTTP request parameter.

It is set to request_locale by default.

attributeName It specifies the name of the session key to store the locale. It is WW_TRANS_I18N_LOCALE by default.

Copyright © 2010 Accenture All Rights Reserved.

Struts 2 Tiles Framework Integration

• There are following advantages of tiles framework: •

Customization by centralized page

: – We can customize the layout of all the pages by single page (centralized page) only.

Code reusability

: – A single part e.g. header or footer can be used in many pages. So it saves coding.

Easy to modify

: – If any part (tile) is modified, we don't need to change many pages.

Easy to remove

: – If any part (tile) of the page is removed, we don't need to remove the code from all the pages. We can remove the tile from our layout manager page.

Copyright © 2010 Accenture All Rights Reserved.

Struts 2 Tiles Application Steps

Add tiles library in application

Define Struts2TilesListener in web.xml file

Create the input page

Create the Action class

Extend the tiles-default package in your package and define all the result type as tiles in struts.xml file

Create the tiles.xml file and define all the tiles definitions

Create the LayoutManager page and create the View components

Copyright © 2010 Accenture All Rights Reserved.

Results & Result Types

• The next step after executing the business logic is to display the view using the

tag.

• Struts2 does not tie developer up with using JSP as the view technology as MVC paradigm is to keep the layers separate and highly configurable.

• Struts comes with a number of predefined

result types

and default result type is

dispatcher

, which is used to dispatch to JSP pages. • Struts allow to use other markup languages for the view technology like

Velocity, Freemaker, XSLT

and

Tiles

to present the results.

Copyright © 2010 Accenture All Rights Reserved.

Predefined Result Types

• Dispatcher Result (default) - It's used to forward to a servlet, JSP, HTML page on the server. It uses the

RequestDispatcher.forward()

method.

• Redirect Action Result – It is used to redirect to another action mapping.

• Chain Result - This result invokes an entire other action, complete with it's own interceptor stack and result.

• Redirect Result - The

redirect

result type calls the standard

response.sendRedirect()

method, causing the browser to create a new request to the given location.

Copyright © 2010 Accenture All Rights Reserved.

Setting a default Result Type

Copyright © 2010 Accenture All Rights Reserved.

Data Tags

Property Set Push Bean Action Output value of an expression Create temporary variable Place object on top of value stack Push JavaBean onto the value stack Render URI or execute action Copyright © 2010 Accenture All Rights Reserved.

Property Tag

Copyright © 2010 Accenture All Rights Reserved.

Set Tag

Hello, How are you?

Copyright © 2010 Accenture All Rights Reserved.

Bean Tag

<%@ taglib prefix="s" uri="/tags" %>

  • Copyright © 2010 Accenture All Rights Reserved.

    Control Tags

    • iterator Loop over collections of objects • if, else, elseif Invoke conditional logic Copyright © 2010 Accenture All Rights Reserved.

    Type Conversion

    • Allows complex objects conversions to strings and vice versa – E.g. from Point class to (3,5) string • Bulilt-in type conversion – String – boolean - Boolean – char - Character – int - Integer, float / Float, long / Long, double / Double – dates - uses the SHORT format – arrays – collections Copyright © 2010 Accenture All Rights Reserved.

    Debugging

    • First enable debugging in struts.properties file – devmode=true • Two modes Xml mode -> formats framework objects as an XML document Console mode -> provides a OGNL command line interpreter • Append to URL – debug=xml or console

    http://localhost:8081/struts2/example/Welcome.action?

    debug=xml

    Copyright © 2010 Accenture All Rights Reserved.

    Development Mode

    • Reloads resource bundles on every request – Change properties files and changes will be reflected on next request – No need to restart the server • Change in struts.xml

    OR

    Add in struts.properties

    devMode=true Copyright © 2010 Accenture All Rights Reserved.

    Questions and Comments

    • What questions or comments do you have?

    Copyright © 2010 Accenture All Rights Reserved. 74