Advanced Struts

Embed Size (px)

Citation preview

  • 8/14/2019 Advanced Struts

    1/158

    1

    Advanced Struts

  • 8/14/2019 Advanced Struts

    2/158

    2

    Sang Shin

    [email protected]

    Java Technology EvangelistSun Microsystems, Inc.

  • 8/14/2019 Advanced Struts

    3/158

    3

    Disclaimer & Acknowledgments

    Even though Sang Shin is a full-time employee of SunMicrosystems, the content in this presentation is created as hisown personal endeavor and thus does not reflect any officialstance of Sun Microsystems.

    Sun Microsystems is not responsible for any inaccuracies in thecontents.

    Acknowledgments:

    I borrowed from presentation slides from the following sources Using the Struts framework presentation material from Sue Spielman of

    Switchback Software ([email protected]) Struts' user's guide is also used in creating slides and speaker notes

    Source code examples are from Cookbook example originally written by

    I also used Programming Jakarta Struts book written by Chuck Cavaness

  • 8/14/2019 Advanced Struts

    4/158

    4

    Revision History

    12/01/2003: version 1: created by Sang Shin 04/09/2004: version 2: speaker notes are polished a bit Things to do

    speaker notes need to be added more example codes need to be added

    javascript slides need to be added

  • 8/14/2019 Advanced Struts

    5/158

    5

    Advanced Struts Topics

    Extending & customizing Struts framework

    Plug-In API (1.1)

    DynaActionForm (1.1)

    Validation framework (1.1)

    Declarative exception handling (1.1)

    Multiple application modules support (1.1)

  • 8/14/2019 Advanced Struts

    6/158

    6

    Advanced Struts Topics

    Accessing database

    Struts-EL tag library

    Struts and security Struts utility classes Nested tag library

    Differences between Struts 1.0 and 1.1 Roadmap

  • 8/14/2019 Advanced Struts

    7/1587

    Extending &Customizing

    Struts Framework

  • 8/14/2019 Advanced Struts

    8/1588

    Extending Struts Framework

    Struts framework is designed withextension and customization in mind It provides extension hooks

    Validator and Tiles use these extension hooks

    Extend the framework only ifdefaultsetting does not meet your needs

    There is no guarantee on the backwardcompatibility in future version of Struts if you areusing the extension

  • 8/14/2019 Advanced Struts

    9/1589

    Extension/Customization

    Mechanisms of the Framework Plug-in mechanism (1.1)

    Extending framework classes (1.1) Extending Struts configuration classes

    Extending ActionServlet class

    Extending RequestProcessorclass

    Extending Action class DispatchAction (1.1) Using multiple configuration files (1.1)

  • 8/14/2019 Advanced Struts

    10/15810

    Extension/Customization:Plug-in Mechanism

  • 8/14/2019 Advanced Struts

    11/15811

    What is a Plug-in?

    Any Java class that you want to initializewhen Struts application starts up anddestroy when the application shuts down

    Any Java class that implementsorg.apache.struts.action.Plugin interface

    public interface PlugIn {

    public void init(ActionServlet servlet,ApplicationConfig config)

    throws ServletException;

    public void destroy();

    }

  • 8/14/2019 Advanced Struts

    12/158

    12

    Why Plug-in?

    Before Struts 1.1 (in Struts 1.0), you had tosubclass ActionServlet to initializeapplication resources at startup time

    With plugin mechanism (in Struts 1.1), youcreate Plugin classes and configure them

    Generic mechanism

    Struts framework itself uses plugin mechanism forsupporting Validator and Tiles

  • 8/14/2019 Advanced Struts

    13/158

    13

    How do you configure Plug-in's?

    Must be declared in struts-config.xml via element

    3 example plug-in's in struts-example sample

    application

  • 8/14/2019 Advanced Struts

    14/158

    14

    How do Plug-in's get called?

    During startup of a Struts application,ActionServlet calls init() method of eachPlug-in configured

    Plug-ins are called in the order they areconfigured in struts-config.xml file

  • 8/14/2019 Advanced Struts

    15/158

    15

    init() of MemoryDatabasePlugin in

    struts-example sample applicationpublic final classMemoryDatabasePlugIn implements PlugIn {

    .../*** Initialize and load our initial database from persistent storage.*

    * @param servlet The ActionServlet for this web application* @param config The ApplicationConfig for our owning module** @exception ServletException if we cannot configure ourselves correctly*/

    public void init(ActionServlet servlet, ModuleConfig config)throws ServletException {

    log.info("Initializing memory database plug in from '" +pathname + "'");

    // Remember our associated configuration and servletthis.config = config;this.servlet = servlet;

  • 8/14/2019 Advanced Struts

    16/158

    16

    Continued... // Construct a new database and make it available

    database = new MemoryUserDatabase();try {

    String path = calculatePath();if (log.isDebugEnabled()) {

    log.debug(" Loading database from '" + path + "'");

    }database.setPathname(path);database.open();

    } catch (Exception e) {log.error("Opening memory database", e);throw new ServletException("Cannot load database from '" +

    pathname + "'", e);}

    // Make the initialized database availableservlet.getServletContext().setAttribute(Constants.DATABASE_KEY,

    database);

    // Setup and cache other required datasetupCache(servlet, config);

    }

  • 8/14/2019 Advanced Struts

    17/158

    17

    destroy() of MemoryDatabasePlugin instruts-example1 sample code

    public final classMemoryDatabasePlugIn implements PlugIn {.../*** Gracefully shut down this database, releasing any resources* that were allocated at initialization.*/

    public void destroy() {

    log.info("Finalizing memory database plug in");

    if (database != null) {try {

    database.close();} catch (Exception e) {

    log.error("Closing memory database", e);}

    }

    servlet.getServletContext().removeAttribute(Constants.DATABASE_KEY);database = null;servlet = null;database = null;

    config = null;

  • 8/14/2019 Advanced Struts

    18/158

    18

    Extension/Customization:

    Extending StrutsFramework Classes

  • 8/14/2019 Advanced Struts

    19/158

    19

    Extending Configuration Classes

    org.apache.struts.config package containsall the classes that are in-memoryrepresentations of all configuration

    information in struts-config.xml file ActionConfig, ActionMapping, ExceptionConfig,

    PluginConfig, MessageResourcesConfig,ControllerConfig, DataSourceConfig,

    FormBeanConfig, etc You extend these classes and then specify

    the extended class with class nameattribute in struts-config.xml

  • 8/14/2019 Advanced Struts

    20/158

    20

    Extending ActionServlet Class In Struts 1.0, it is common to extend

    ActionServlet class since There was no plugin mechanism

    ActionServlet handles all the controller functionalitysince there was no RequestProcessor

    Rarely needed in Struts 1.1 Change web.xml

    action

    myPackage.myActionServlet

  • 8/14/2019 Advanced Struts

    21/158

    21

    Extending RequestProcessor Class

    Via element in struts-config.xml process() method ofRequestProcessorclass is

    called before ActionForm class is initialized and

    execute() method ofAction object get called Example in struts-cookbook sample code

  • 8/14/2019 Advanced Struts

    22/158

    22

    Extending Action Classes

    Useful to create a base Action class whencommon logic is shared among manyAction classes

    Create base Action class first then subclass it foractual Action classes

  • 8/14/2019 Advanced Struts

    23/158

    23

    Extension/Customization:DispatchAction

  • 8/14/2019 Advanced Struts

    24/158

    24

    Why DispatchAction?

    To allow multiple related operations toreside in a single Action class Instead of being spread over multiple Action

    classes To allow common logic to be shared

    Related operations typically share some commonbusiness logic

  • 8/14/2019 Advanced Struts

    25/158

    25

    How to use DispatchAction?

    Create a class that extends DispatchAction(instead ofAction)

    In a new class, add a method for everyfunction you need to perform on the service The method has the same signature as the

    execute() method of an Action class

    Do not override execute() method Because DispatchAction class itself provides

    execute() method

    Add an entry to struts-config.xml

  • 8/14/2019 Advanced Struts

    26/158

    26

    Example: ItemAction class extendsDispatchActionpublic class ItemActionextends DispatchAction {

    public ActionForward addItem(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception {

    try {// Code for item add

    } catch(Exception ex) {//exception}}

    public ActionForward deleteItem(ActionMapping mapping,ActionForm form,

    HttpServletRequest request,HttpServletResponse response) throws

    Exception {try {

    // Code for item deletion}catch(Exception ex){//exception}

    }}

  • 8/14/2019 Advanced Struts

    27/158

    27

    Example: struts-config.xml

    The method can be invoked using a URL, like this:ItemAction.do?actionType=addItem

  • 8/14/2019 Advanced Struts

    28/158

    28

    Extension/Customization:ForwardAction

  • 8/14/2019 Advanced Struts

    29/158

    29

    Why ForwardAction?

    If you have the case where you don't need toperform any logic in the Action but would liketo follow the convention of going through an

    Action to access a JSP, the ForwardActioncan save you from creating many emptyAction classes

    The benefit of the ForwardAction is that you

    don't have to create an Action class of yourown All you have to do is to declaratively configure an

    Action mapping in your Struts configuration file.

  • 8/14/2019 Advanced Struts

    30/158

    30

    Example: ForwardAction

    Suppose that you had a JSP page calledindex.jsp and instead of calling this pagedirectly, you would rather have the application

    go through an Action class http://hostname/appname/home.do

  • 8/14/2019 Advanced Struts

    31/158

    31

    Example: ForwardAction

    Another way for forwarding

  • 8/14/2019 Advanced Struts

    32/158

    32

    Extension/Customization:

    Using MultipleStruts Configuration File

  • 8/14/2019 Advanced Struts

    33/158

    33

    Multiple Configuration Files

    Useful for multi-developer environment At least, a single struts-config.xml file is not a

    bottleneck anymore

    Different from Multiple modules support

  • 8/14/2019 Advanced Struts

    34/158

    34

    web.xml of struts-example

    action

    org.apache.struts.action.ActionServlet

    config

    /WEB-INF/struts-config.xml,

    /WEB-INF/struts-config-registration.xml

    1

  • 8/14/2019 Advanced Struts

    35/158

    35

    struts-config-registration.xml of

    struts-example sample app

  • 8/14/2019 Advanced Struts

    36/158

    36

    struts-config-registration.xml of

    struts-example

  • 8/14/2019 Advanced Struts

    37/158

    37

    DynaActionForm

    (Introduced in 1.1)

  • 8/14/2019 Advanced Struts

    38/158

    38

    Why DynaActionForm?

    Issues with using ActionForm ActionForm class has to be created in Java

    programming language

    For each HTML form page, a new ActionFormclass has to be created

    Every time HTML form page is modified (aproperty is added or remove), ActionForm class

    has to be modified and recompiled DynaActionForm support is added to Struts

    1.1 to address these issues

  • 8/14/2019 Advanced Struts

    39/158

    39

    What is DynaActionForm? org.apache.struts.action.DynaActionForm

    extends ActionForm class

    In DynaActionForm scheme, Properties are configured in configuration file

    rather than coding

    reset() method resets all the properties back totheir initial values

    You can still subclass DynaActionForm to overridereset() and/or validate() methods

    Version exists that works with Validator framework toprovide automatic validation

  • 8/14/2019 Advanced Struts

    40/158

    40

    How to Configure DynaActionForm?

    Configure the properties and their types inyourstruts-config.xml file add one or more elements for

    each element

  • 8/14/2019 Advanced Struts

    41/158

    41

    Example from struts-examplesSteve

  • 8/14/2019 Advanced Struts

    42/158

    42

    Types Supported by

    DynaActionForm java.lang.BigDecimal, java.lang.BigInteger boolean and java.lang.Boolean byte and java.lang.Byte char and java.lang.Character java.lang.Class, double and java.lang.Double float and java.lang.Float int and java.lang.Integer long and java.lang.Long short and java.lang.Short java.lang.String

    java.sql.Date, java.sql.Time, java.sql.Timestamp

  • 8/14/2019 Advanced Struts

    43/158

    43

    How to perform Validation with

    DynaActionForm? DynaActionForm does not provide default

    behavior for validate() method

    You can subclass and override validate() methodbut it is not recommended

    Use Validator Framework Use DynaValidatorForm class (instead of

    DynaActionForm class) DynaValidatorForm class extends

    DynaActionForm and provides basic fieldvalidation based on an XML file

  • 8/14/2019 Advanced Struts

    44/158

    44

    Example from strut-example

    sample application

  • 8/14/2019 Advanced Struts

    45/158

    45

    Validation Framework(added to Struts 1.1 Core)

  • 8/14/2019 Advanced Struts

    46/158

    46

    Why Struts Validation

    Framework? Issues with writing validate() method in

    ActionForm classes You have to write validate() method for each

    ActionForm class, which results in redundant code Changing validation logic requires recompiling

    Struts validation framework addresses

    these issues Validation logic is configured using built-in

    validation rules as opposed to writing it in Javacode

  • 8/14/2019 Advanced Struts

    47/158

    47

    What is Struts Validation

    Framework? Originated from generic Validator

    framework from Jakarta

    Struts 1.1 includes this by default Allows declarative validation for many fields

    Formats Dates, Numbers, Email, Credit Card, Postal Codes

    Lengths Minimum, maximum

    Ranges

  • 8/14/2019 Advanced Struts

    48/158

    48

    Validation Rules

    Rules are tied to specific fields in a form Basic Validation Rules are built-in in the

    Struts 1.1 core distribution e.g. required, minLength, maxLength, etc.

    The built-in validation rules come withJavascript that allows you to do client side

    validation Custom Validation rules can be created and

    added to the definition file. Can also define regular expressions

  • 8/14/2019 Advanced Struts

    49/158

    49

    Validation Framework:

    How toconfigure and useValidation framework?

  • 8/14/2019 Advanced Struts

    50/158

    50

    Things to do in order to use

    Validator framework Configure Validator Plug-in Configure validation.xml file (and validation-

    rules.xml file) Extend Validator ActionForms or Dynamic

    ActionForms Set validate=true on Action Mappings Include the tag for client

    side validation in the form's JSP page

  • 8/14/2019 Advanced Struts

    51/158

    51

    How to Configure Validator Plug-

    in Validator Plug-in should be configured in

    the Struts configuration file

    Just add the following element

  • 8/14/2019 Advanced Struts

    52/158

    52

    Two Validator Configuration Files

    validation-rules.xml Contains global set of validation rules

    Provided by Struts framework

    validation.xml Application specific

    Provided by application developer

    It specifies which validation rules from validation-rules.xml file are used by a particular ActionForm

    No need to write validate() code in ActionFormclass

  • 8/14/2019 Advanced Struts

    53/158

    53

    Validation Framework:validation-rules.xml

  • 8/14/2019 Advanced Struts

    54/158

    54

    Built-in (basic) Validation Rules

    required, requiredif minlength maxlength mask byte, short, integer, long, float, double date, range, intRange, floatRange creditCard, email

  • 8/14/2019 Advanced Struts

    55/158

    55

    validation-rules.xml: Built-inrequired validation rule

    var isValid = true;...

  • 8/14/2019 Advanced Struts

    56/158

    56

    validation-rules.xml: Built-in

    minlength validation rule

    var isValid = true;var focusField = null;...

  • 8/14/2019 Advanced Struts

    57/158

    57

    Attributes of

    Element name: logical name of the validation rule classname, method: class and method that

    contains the validation logic methodParams: comma-delimited list of

    parameters for the method msg: key from the resource bundle

    Validator framework uses this to look up a messagefrom Struts resource bundle

    depends: other validation rules that shouldbe called first

  • 8/14/2019 Advanced Struts

    58/158

    58

    Built-in Error Messages From Validator

    Framework# Built-in error messages for validator framework checks# You have to add the following to your application's resource bundleerrors.required={0} is required.errors.minlength={0} cannot be less than {1} characters.

    errors.maxlength={0} cannot be greater than {2} characters.errors.invalid={0} is invalid.errors.byte={0} must be an byte.errors.short={0} must be an short.errors.integer={0} must be an integer.errors.long={0} must be an long.

    errors.float={0} must be an float.errors.double={0} must be an double.errors.date={0} is not a date.errors.range={0} is not in the range {1} through {2}.errors.creditcard={0} is not a valid credit card number.errors.email={0} is an invalid e-mail address.

  • 8/14/2019 Advanced Struts

    59/158

    59

    Validation Framework:validation.xml

  • 8/14/2019 Advanced Struts

    60/158

    60

    validation.xml: logonForm (from

    struts-examples sample code)

    maxlength16

    minlength3

  • 8/14/2019 Advanced Struts

    61/158

    61

    validation.xml: logonForm (from

    struts-examples sample code)

    maxlength16

    minlength3

  • 8/14/2019 Advanced Struts

    62/158

    62

    validation.xml: registrationForm (from

    struts-examples sample code)

    -

  • 8/14/2019 Advanced Struts

    63/158

    63

    Element

    Defines a set of fields to be validated

    Attributes Name: Corresponds name attribute of

    in struts-config.xml

  • 8/14/2019 Advanced Struts

    64/158

    64

    struts-config.xml: logonForm (from

    struts-examples sample code)

  • 8/14/2019 Advanced Struts

    65/158

    65

    Element

    Corresponds to a property in an ActionForm

    arg3?, var*)>

    Attributes property: name of a property (in an ActionForm) that

    is to be validated

    depends: comma-delimited list of validation rules to

    apply against this field All validation rules have to succeed

  • 8/14/2019 Advanced Struts

    66/158

    66

    Element: child

    element Allows you to specify an alternate message

    for a field element

    name: specifies rule with which the msg is used, shouldbe one of the rules in validation-rules.xml

    key: specifies key from the resource bundle that shouldbe added to the ActionError if validation fails

    resource: if set to false, the value of key is taken asliteral string

  • 8/14/2019 Advanced Struts

    67/158

    67

    Element: child

    element

    Are used to pass additional values to the message

    is the 1st

    replacement and is the 2nd

    replacement, and so on

  • 8/14/2019 Advanced Struts

    68/158

    68

    Element: child

    element......

    Set parameters that a field element may

    need to pass to one of its validation rulessuch as minimum and miximum values in arange validation

    Referenced by elements using ${var:var-name} syntax

  • 8/14/2019 Advanced Struts

    69/158

    69

    Validation Framework:

    How do you useActionForm with

    Validator?

  • 8/14/2019 Advanced Struts

    70/158

    70

    ActionForm and Validator

    You cannot use ActionForm class with theValidator Instead you need to use special subclasses of

    ActionForm class

    Validator supports two types specialActionForms Standard ActionForms

    ValidatorActionForm

    ValidatorForm

    Dynamic ActionForms DynaValidatorActionForm

    DynaValidatorForm

  • 8/14/2019 Advanced Struts

    71/158

    71

    Choices You have

    Standard ActionForms or DynamicActionForms? (rehash) If you want to specify ActionForms declaratively,

    use dynamic ActionForms

    xValidatorActionForm or xValidatorForm? Use xValidatorActionForm if you want more fine-

    grained control over which validation rules areexecuted

    In general, xValidatorForm should be sufficient

  • 8/14/2019 Advanced Struts

    72/158

    72

    Validation Framework:struts-exampleSample code

  • 8/14/2019 Advanced Struts

    73/158

    73

    struts-config.xml:

    DynaValidatorForm

  • 8/14/2019 Advanced Struts

    74/158

    74

    validation-rules.xml: Built-inrequired validation rule

    var isValid = true;...

  • 8/14/2019 Advanced Struts

    75/158

    75

    validation-rules.xml: Built-in

    minlength validation rule

    var isValid = true;var focusField = null;...

  • 8/14/2019 Advanced Struts

    76/158

    76

    validation.xml: logonForm

    maxlength16

    minlength3

  • 8/14/2019 Advanced Struts

    77/158

    77

    ApplicationResources.Properties

    # Standard error messages for validator framework checkserrors.required={0} is required.errors.minlength={0} cannot be less than {1} characters.errors.maxlength={0} cannot be greater than {2} characters.errors.invalid={0} is invalid.errors.byte={0} must be an byte.

    errors.short={0} must be an short.errors.integer={0} must be an integer.errors.long={0} must be an long.errors.float={0} must be an float.errors.double={0} must be an double.errors.date={0} is not a date.errors.range={0} is not in the range {1} through {2}.

    errors.creditcard={0} is not a valid credit card number.errors.email={0} is an invalid e-mail address.

  • 8/14/2019 Advanced Struts

    78/158

    78

    LogonForm Validation: required

  • 8/14/2019 Advanced Struts

    79/158

    79

    LogonForm Validation: minlength

  • 8/14/2019 Advanced Struts

    80/158

    80

    LogonForm Validation: maxlength

  • 8/14/2019 Advanced Struts

    81/158

    81

    struts-config.xml: Regular ActionFormclass (actually extension of it)

  • 8/14/2019 Advanced Struts

    82/158

    82

    SubscriptionForm class

    public final class SubscriptionForm extends ActionForm {...public String getAction() {

    return (this.action);}

    public void setAction(String action) {this.action = action;

    }...

    public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {

    ...}

    ...}

  • 8/14/2019 Advanced Struts

    83/158

    83

    Validation Framework:

    How to performClient-side Validationusing JavaScript?

  • 8/14/2019 Advanced Struts

    84/158

    84

    JavaScript Support in Validator

    Framework The Validator framework is also capable of

    generating JavaScript for your Strutsapplication using the same framework as for

    server-side validation By using a set of JSP custom tags designed

    specifically for this purpose

  • 8/14/2019 Advanced Struts

    85/158

    85

    Configuring validation-rules.xml

    for JavaScript A custom tag is used to generate client-side

    validation based on ajavascript attributebeing present within the element

    in the validation-rules.xml file Use thecustom tag in your JSP page

    The text from element is written to the

    JSP page to provide client-side validation

  • 8/14/2019 Advanced Struts

    86/158

    86

    Configuring validation-rules.xml forJavaScript

    var isValid = true;...

  • 8/14/2019 Advanced Struts

    87/158

    87

    Validation Rules for the

    logonForm in validation.xml

    ...

    ...

  • 8/14/2019 Advanced Struts

    88/158

  • 8/14/2019 Advanced Struts

    89/158

    89

    logon.jsp Page (from struts-

    example sample code)

  • 8/14/2019 Advanced Struts

    90/158

    90

    Things You Have to Do in your JSP

    Page You will have to add an onsubmit event

    handler for the form manually When the form is submitted, the

    validateLogonForm( ) JavaScript function willbe invoked The validation rules will be executed, and if one or

    more rules fail, the form will not be submitted.

  • 8/14/2019 Advanced Struts

    91/158

    91

    Things You Have to Do in your JSP

    Page The tag generates a

    function with the name validateXXX( ) ,where XXX is the name of the ActionForm Thus, if your ActionForm is called logonForm, the

    javascript tag will create a JavaScript function calledvalidateLogonForm( ) that executes the validationlogic

    This is why the onsubmit( ) event handler called thevalidateLogonForm( ) function.

  • 8/14/2019 Advanced Struts

    92/158

    92

    logon.jsp Page (from struts-

    example sample code)

    :

    ...

  • 8/14/2019 Advanced Struts

    93/158

    93

    Validation Framework:

    I18N andValidation

  • 8/14/2019 Advanced Struts

    94/158

    94

    I18N and Validator Validator framework uses Struts resource

    bundle element in validation.xml supports

    language, country, variant...

    ...

    ...

  • 8/14/2019 Advanced Struts

    95/158

    95

    Validation Framework:

    Advanced Featuresof Validator

  • 8/14/2019 Advanced Struts

    96/158

    96

    Advanced Features

    Creating custom validators Using programmatic validation along with

    Validator

  • 8/14/2019 Advanced Struts

    97/158

    97

    DeclarativeException Handling

  • 8/14/2019 Advanced Struts

    98/158

    98

    Why Declarative Exception Handling?

    Previously (Struts 1.0), Action class has todeal with all business logic exceptions itself No common exception handling

    Rather difficult to implement

  • 8/14/2019 Advanced Struts

    99/158

    99

    What is Declarative Exception Handling?

    Exception handling policy is declarativelyspecified in struts-config.xml Exceptions that may occur

    What to do if exceptions occur

    Can be global and per-Action From a particular Exception class or super class

    To an application-relative path

    Requires a small change to your Action toleverage this feature ...

  • 8/14/2019 Advanced Struts

    100/158

    100

    Example in struts-example

  • 8/14/2019 Advanced Struts

    101/158

    101

    How Does it Work?

    When an Exception is thrown inside execute()ofAction class, processException() method ofRequestProcessorclass is called

    processException() method checks if element is configured for thatspecific exception type

    If there is, Default exception handler creates and stores an

    ActionErrorinto the specified scope

    Control is then forwarded to the resource specifiedin path attribute

  • 8/14/2019 Advanced Struts

    102/158

    102

    Example in struts-example1

    public ActionForwardexecute

    (ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response)

    throws Exception {

    ...

    throw new PasswordExpiredException(...);

    ...

    }

  • 8/14/2019 Advanced Struts

    103/158

    103

    Customizing Exception Handling

    Create a class that extendsorg.apache.struts.action.ExceptionHandler Override execute() method

    public ActionForward execute( Exception ex,ExceptionConfig exConfig,

    ActionMapping mapping,

    ActionForm formInstance,

    HttpServletRequest request,HttpServletResponse response

    ) throws ServletException;

  • 8/14/2019 Advanced Struts

    104/158

    104

    Customizing Exception Handling

    Configure the Custom Exception Handler(globally or per action basis)

  • 8/14/2019 Advanced Struts

    105/158

    105

    Customizing Exception Handling

    Multiple Custom Exception Handlers

  • 8/14/2019 Advanced Struts

    106/158

    106

    Application Modules

    Wh t A li ti M d l ?

  • 8/14/2019 Advanced Struts

    107/158

    107

    What are Application Modules?

    Allows a single Struts application to be splitinto multiple modules Each module has its own Struts configuration file,

    JSP pages, Actions

    Multiple Application Module

  • 8/14/2019 Advanced Struts

    108/158

    108

    Multiple Application ModuleSupport

    Necessary for large scale applications Allows parallel development

    Design goals: Support multiple independent Struts configurationfiles in the same application

    Modules are identified by an "application prefix"that follows the context path

    Existing Struts-based applications should be ableto be installed individually, or as a sub-application,with no changes to the pages, Actions, formbeans, or other code

    Multiple Application Modules Support

  • 8/14/2019 Advanced Struts

    109/158

    109

    Multiple Application Modules Support

    Implications of the design goals: "Default" sub-application with a zero-length prefix

    (like the ROOT context in Tomcat)

    "Context-relative" paths must now be treated as

    "sub-application-relative" ActionServlet initialization parameters migrate to

    the Struts configuration file

    Controller must identify the relevant sub-application, and make its resources available (asrequest attributes)

    APIs must be reviewed for assumptions aboutthere being (for example) only one set ofActionMappings

  • 8/14/2019 Advanced Struts

    110/158

    110

    Application Modules:

    How to configuremodules

    How to set up and use multiple

  • 8/14/2019 Advanced Struts

    111/158

    111

    How to set up and use multiple

    Application Modules? Prepare a config file for each module. Inform the controller of your module.

    Use actions to refer to your pages.

  • 8/14/2019 Advanced Struts

    112/158

    112

    Informing the Controller

    In web.xml...config

    /WEB-INF/conf/struts-default.xmlconfig/module1/WEB-INF/conf/struts-module1.xml

    ...

  • 8/14/2019 Advanced Struts

    113/158

    113

    Application Modules:How to switch modules

  • 8/14/2019 Advanced Struts

    114/158

    114

    Methods for Switching Modules

    Two basic methods to switching from onemodule to another Use a forward (global or local) and specify the

    contextRelative attribute with a value oftrue Use the built-in

    org.apache.struts.actions.SwitchAction

  • 8/14/2019 Advanced Struts

    115/158

    115

    Global Forward......

    ......

  • 8/14/2019 Advanced Struts

    116/158

    116

    Local Forward.........

    ......

  • 8/14/2019 Advanced Struts

    117/158

    117

    org.apache.struts.actions.SwitchAction

    .........

  • 8/14/2019 Advanced Struts

    118/158

    118

    How to change module To change module, use URI

    http://localhost:8080/toModule.do?prefix=/moduleB&page=/index.do

    If you are using the "default" module as wellas "named" modules (like "/moduleB"), youcan switch back to the "default" modulewith a URI

    http://localhost:8080/toModule.do?prefix=&page=/index.do

  • 8/14/2019 Advanced Struts

    119/158

    119

    Struts ELTag library

    St t EL E t i

  • 8/14/2019 Advanced Struts

    120/158

    120

    Struts EL Extension

    Extension of the Struts tag library Uses the expression evaluation engine in the

    Jakarta Taglibs implementation of the JSP

    Standard Tag Library (version 1.0) to evaluateattribute values Some of the Struts tags were not ported to this

    library

    their functionality was entirely supplied by theJSTL

    Requires the use of the Struts tag library, andthe Java Server Pages Standard Tag Library

    T M i

  • 8/14/2019 Advanced Struts

    121/158

    121

    Tag Mapping

    Every Struts tag that provides a feature thatis not covered by the JSTL (1.0) library ismapped into the Struts-EL library

    Bean Tag Library Tags NOT Implementedin Struts-EL cookie (in Struts): c:set, EL (in JSTL)

    define (in Struts), c:set, EL (In JSTL)

    H t St t EL

  • 8/14/2019 Advanced Struts

    122/158

    122

    How to use Struts EL

    Struts

    Struts EL

  • 8/14/2019 Advanced Struts

    123/158

    123

    Struts &Security

    JAAS

  • 8/14/2019 Advanced Struts

    124/158

    124

    JAAS

    Struts 1.1 and later offers direct support forthe standard Java Authentication andAuthorization Service (JAAS)

    You can now specify security roles on anaction-by-action basis

    SSL E tension (ssle t)

  • 8/14/2019 Advanced Struts

    125/158

    125

    SSL Extension (sslext)

    Extension to Struts 1.1 http://sslext.sourceforge.net

    Extends the ActionConfig class,

    RequestProcessor, and Plugin classes todefine a framework where developers mayspecify the transmission protocol behavior forStruts applications

    Within the Struts configuration file, developersspecify which action requests require HTTPStransmission and which should use HTTP

    SSL Extension (sslext)

  • 8/14/2019 Advanced Struts

    126/158

    126

    SSL Extension (sslext)

    Can also specify whether to redirect"improperly-protocoled" requests to the correctprotocol

    and tag extension Struts actions specified in either of these tags are

    analyzed to determine the protocol that should beused in requesting that action

    The HTML generated by these tags will specify theproper protocol

  • 8/14/2019 Advanced Struts

    127/158

    127

    Commons:DynaBeans

    CO O S S

  • 8/14/2019 Advanced Struts

    128/158

    128

    COMMONS-BEANUTILS

    Pluggable type converters Mapped properties

    contact.phone(Work)

    DynaBeans Transparently supported by BeanUtils and

    PropertyUtils

    Commons-Beanutils --

  • 8/14/2019 Advanced Struts

    129/158

    129

    Commons Beanutils

    DynaBeanspublic interface DynaBean {public Object get(String name);

    public Object get(String name, int index);

    public Object get(String name, String key);

    public void set(String name, Object value);

    public void set(String name, int index, Objectvalue);

    public void set(String name, String key,Object value);

    }

  • 8/14/2019 Advanced Struts

    130/158

    130

    Struts Utilities

    Utilities

  • 8/14/2019 Advanced Struts

    131/158

    131

    Utilities org.apache.struts.utilpackage Families of classes that solve common

    web app problems.

    Suitable for general Java programmingand are worth checking out Utilities classes include:

    Beans & Properties

    Collection Classes JDBC connection pool

    Message Resources

    Utility Classes

  • 8/14/2019 Advanced Struts

    132/158

    132

    Utility Classes common-*.jar Now required for Struts

    Might require some package renaming for 1.0.2 Strutsapps

    Many utilities are now located in the JakartaCommons project http://jakarta.apache.org/commons/

    BeanUtils Package org.apache.commons.beanutils

    Collections Package org.apache.commons.collections

    Digester Package org.apache.commons.digester

  • 8/14/2019 Advanced Struts

    133/158

    133

    BeanUtil & PropertyUtil

    Relies on using Java Reflection tomanipulate Java Beans

    Used throughout Struts (IteratorTag,

    WriteTag) Need to make sure you have a valid bean!

    Null constructor

    Public class declaration

    Mutator/Accessor methods

    XML Parsing

  • 8/14/2019 Advanced Struts

    134/158

    134

    XML Parsing

    Digester package provides for rules-basedprocessing of arbitrary XML documents.

    Higher level, more developer-friendly

    interface to SAX events Digester automatically navigates the element

    hierarchy of the XML document Element Matching Patterns

    Processing Rule

  • 8/14/2019 Advanced Struts

    135/158

    135

    AccessingDatabase

    R d ti Fi t

  • 8/14/2019 Advanced Struts

    136/158

    136

    Recommendation First Database access logic belong to business

    logic (Model) Action class should be just a thin layer to

    Model All the database access code should be

    encapsulated in the business logic

    Struts doesn't know what persistent layer you are

    using (or even if there is a persistence layer) Use database access logic of your model

    component (EJB, JDO, etc.) if possible

  • 8/14/2019 Advanced Struts

    137/158

    Example in struts-config xml

  • 8/14/2019 Advanced Struts

    138/158

    138

    Example in struts-config.xml

  • 8/14/2019 Advanced Struts

    139/158

  • 8/14/2019 Advanced Struts

    140/158

    140

    Struts andJ2EE Patterns

    Struts and Core J2EE Patterns

  • 8/14/2019 Advanced Struts

    141/158

    141

    St uts a d Co e J atte s

    Client

    Action

    ServletAction

    Action

    Forward

    Action

    FormJSP View

    Request

    Response

    uses

    Controller Model

    View Helper

    View

    ActionMapping

    (xml)

    Service

    Interface

    Business

    Service

    Business

    Delegate

    Service

    Locator

    Struts and Core J2EE Patterns

  • 8/14/2019 Advanced Struts

    142/158

    142

    Composite View

    Front Controller Business Delegate

    Compsite Entity

    DataTransfer Object

    Session Facade

    DataTransfer Object

    P resentationRequestContr oller Cr ea teAccountD ispatcher User AccountManager Delegate

    EJBSessionBean

    UserA ccountManagerEJB

    EJBEntityBean

    UserA ccountEJB

    EJBEntityB ean

    CreditCardEJB

    CreditCardValuesUserAccountValues

    ServerPagetemplate.jsp

    ServerPagemenu.jsp

    JSPInclude

    + themenu.jsp

    ServerPagenew_account.jsp

    ServerPagenew_account_confirm.jsp

    ActionActionServlet

  • 8/14/2019 Advanced Struts

    143/158

    143

    Nested Tag Library

    The "Nested" Tag Library

  • 8/14/2019 Advanced Struts

    144/158

    144

    The Nested Tag Library

    Brings a nested context to the functionality ofthe Struts custom tag library

    Written in a layer that extends the current

    Struts tags, building on their logic andfunctionality The layer enables the tags to be aware of the tags

    which surround them so they can correctly provide

    the nesting property reference to the Struts system

    The "Nested" Tag Library

  • 8/14/2019 Advanced Struts

    145/158

    145

    The Nested Tag Library Nested tags allow you to establish a default

    bean for nested property references 1:1 correspondence, and identical

    functionality, of other Struts tags Except the "name" property gets set for you

    automatically ...

    Example: Scenario

  • 8/14/2019 Advanced Struts

    146/158

    146

    Example: Scenario Company has many departments

    Company bean has a collection of Departmentbeans

    Each department has many employees Department bean has a collection of Employee

    beans

    Example: Suppose You WantT Di l th f ll i

  • 8/14/2019 Advanced Struts

    147/158

    147

    To Display the following...

    Example: Using JSTL for

  • 8/14/2019 Advanced Struts

    148/158

    148

    gIterating Nested Beans

    COMPANY:

    Department:

    Employee:

    E-mail:


    Example: Using Nested Tag for

  • 8/14/2019 Advanced Struts

    149/158

    149

    p g gDoing the Same ThingCOMPANY:

    Department:

    Employee:

    E-mail:

    Example 2:

  • 8/14/2019 Advanced Struts

    150/158

    150

    Example 2:

    Before using the nested tags:

    After using the nested tags:

  • 8/14/2019 Advanced Struts

    151/158

    151

    Changes BetweenStruts 1.0 & 1.1

    Struts 1 1 ActionServlet

  • 8/14/2019 Advanced Struts

    152/158

    152

    Struts 1.1 ActionServlet

    Introduction of request processor Via RequestProcessorclass

    Handles much of the functionality of ActionServlet

    in Struts1.0 ActionServlet in 1.1 is a thin layer

    Allows developers to customize the requesthandling behavior more easily

    Struts 1 1 Actions

  • 8/14/2019 Advanced Struts

    153/158

    153

    Struts 1.1 Actions

    Method perform() replaced by execute() Backwards compatible

    Change necessary to support declarative

    exception handling Addition ofDispatchAction class

    Supports multiple business methods instead of asingle execute() method

    Allows easy group of related business methods

    Changes to web.xml and

  • 8/14/2019 Advanced Struts

    154/158

    154

    struts-config.xml web.xml

    Serveral initialization parameters removed Uses elements in struts-config.xml

    Supports a few new parameters

    New Features in Struts 1 1

  • 8/14/2019 Advanced Struts

    155/158

    155

    New Features in Struts 1.1

    Plug-ins Dynamic ActionForms

    Multiple application modules Declative exception handling Validator framework

    Nested tags Dependency to Commons projects Action-based authentication

  • 8/14/2019 Advanced Struts

    156/158

    156

    Roadmap

  • 8/14/2019 Advanced Struts

    157/158

  • 8/14/2019 Advanced Struts

    158/158

    Passion!