24-StrutsAdvanced_93

Embed Size (px)

Citation preview

  • 7/28/2019 24-StrutsAdvanced_93

    1/93

    1

    1

    Advanced Struts

    In this presentation, we are going to talk about advanced featuresof Struts. I expect the audience of this presentation has some basicunderstanding on Struts.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    2/93

    2

    2

    Sang Shin

    [email protected]

    Java Technology EvangelistSun Microsystems, Inc.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    3/93

    3

    3

    Disclaimer & Acknowledgments

    ? Even though Sang Shin is a full-time employee of Sun

    Microsystems, 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

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    4/93

    4

    4

    Revision History

    ? 12/01/2003: version 1: created by Sang Shin? 04/09/2004: version 2: speaker notes are polished a bit? 09/01/2005: DynaActionForm and Validation Framework

    slides are separated out into a different file? Things to do

    speaker notes need to be added

    more example codes need to be added

    javascript slides need to be added

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    5/93

    5

    5

    Advanced Struts Topics

    ? Extending & customizing Struts framework Plug-In API (1.1)

    ? ForwardAction (1.1)? DispatchAction (1.1)? Declarative exception handling (1.1)

    ? Multiple application modules support (1.1)

    So this is the first page of the topics we will discuss in this presentation. First,

    we will talk about how to extend and customize Struts framework especiallywith plug-in mechanism. Then we will talk about DynaActionForm. We will

    spend quite a bit of our time talking about Validation and Tiles frameworks.

    Validation framework enables validation through configuration. And Tilesframework enables a flexible way of managing layouts. We will talk a bit on

    declarative exception handling. And then we will talk about how multipleapplication modules can be configured. As you can see all of these features

    are introduced in Struts 1.1.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    6/93

    6

    6

    Advanced Struts Topics

    ? Struts and security

    ? Struts utility classes

    ? Nested tag library

    ? Differences between Struts 1.0 and 1.1

    ? Roadmap

    We will then talk about how to use Struts to access databases. We will also

    talk about how expression language feature of JSTL can be used with Struts.We will spend a bit of time taking about how security features such as SSL can

    be used with Struts. Then we will talk about a few other issues.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    7/93

    7

    7

    Advanced Struts Topics Covered

    in Other Presentations? Struts Tags

    ? Struts Validation Frameworks

    ? Struts and Tiles

    ? Struts and Database Access? Struts Best Practices? Struts Tools

    .

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    8/93

    8

    8

    Extending &Customizing

    Struts Framework

    N ow let's talk about how to extend and customize Strutsframework especially plugin mechanism. We are talking aboutthis topic first because the plugin mechanism is going to be usedby Validator and Tiles frameworks.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    9/93

    9

    9

    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 backward

    compatibility in future version of Struts if you areusing the extension

    One of the reasons why Struts has become such a popular framework is itallows extension and customization in pretty much every facet of its

    framework. In fact, one of the original design goals of Struts isextensibility and customizability. So it is designed with these aspects inmind and as you will see in the following slides, it provides variousextension hooks in its architecture. In fact, several features of Struts suchas Validator and Tiles use these extensions underneath.

    Now Struts framework comes with lots of built-in features so in mostcases you do not need to extend and customize the framework. And when

    you have to, it is recommended that you do it with care because there is noguarantee that your application will work with the next version of theStruts framework.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    10/93

    10

    10

    Extension/Customization

    Mechanisms of the Framework

    ? Plug-in mechanism (1.1)

    ? Extending framework classes (1.1) Extending Struts configuration classes

    ExtendingActionServlet class

    Extending RequestProcessorclass

    ExtendingAction class

    ? Using multiple configuration files (1.1)

    So the primary extension mechanism of Struts is plug-in mechanism,which was introduced as part of Struts 1.1.

    In addition, you can also extend the framework classes. Again, this is notnecessary for most applications.

    We will then talk about how you can use DispatchAction class. Also we

    will talk about how you can use multiple configuration files.

    By the way, all of these features are introduced in Struts 1.1.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    11/93

    11

    11

    Extension/Customization:

    Plug-in Mechanism

    So let's talk about plugin mechanism first.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    12/93

    12

    12

    What is a Plug-in?

    ? Any Java class that you want to initialize

    when Struts application starts up anddestroy when the application shuts down Any Java class that implements

    org.apache.struts.action.Plugin interface

    public interface PlugIn {

    public void init(ActionServlet servlet,

    ApplicationConfig config)

    throws ServletException;

    public void destroy();

    }

    A plugin under Struts context is basically any Java class that implementsorg.apache.struts.action.Plugin interface. As you can see in the slide, the

    Plugin interface has init(..) anddestroy()methods, which are used for one-timeinitialization and cleanup respectively. The initialization occurs when Strutsapplication gets started up and the cleanupoccurs when the application is beingshut down. So inside the init() method, for example, you might want to create adatabase connection, and inside the destroy() method, you might want to closethe database connection.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    13/93

    13

    13

    Why Plug-in?

    ? Before Struts 1.1 (in Struts 1.0), you had to

    subclassActionServlet 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 for

    supporting Validator and Tiles

    So why do we need plugin mechanism? Before plugin is introduced, that isunder Struts 1.0, the only way you can do some initialization is to subclassActionServlet class. Obviously this is not really a convenient way of performingan initialization.

    With plugin mechanism, you create plugin classes and then configure themthrough struts-config.xml file. So, as was mentioned, Struts framework itselfuses plugin mechanism for adding validator and tiles frameworks.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    14/93

    14

    14

    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

    Struts PlugIns are configured using the element within the Strutsconfiguration file. This element has only one valid attribute, 'className', whichis the fully qualified name of the Java class which implements theorg.apache.struts.action.PlugIn interface.

    For PlugIns that require configuration themselves, the nested element is available.

    So this slide shows three elements in the struts-config.xml file of thestruts-examples1 sample code that you find in the hands-on lab/homework

    material you download from the class website.

    The first plugin is ModuleConfigVerifier that verifies module configuration.This plugin comes with Struts. The second is MemoryDatabasePlugin thatprovides in-memory SQL database functionality and the third one is Validator

    plugin.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    15/93

    15

    15

    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

    So how do these plugin's get called? During the startup of a Struts applicatiuon,ActionServlet calls init() method of each plugin configured. And these pluginsare called in the order they are configured in the struts-config.xml. So if theorder of initialization is important, make sure they are configured in the rightorder.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    16/93

    16

    16

    init() of MemoryDatabasePlugin instruts-example sample application

    public 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;

    This is code fragment from the MemoryDatabasePlugin code that comes withstruts-example1 sample code you download from the class website.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    17/93

    17

    17

    Continued...

    // Construct a new database and make it availabledatabase = 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);

    }

    This is the continuation of the init() method of the plugin.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    18/93

    18

    18

    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;

    This is the code fragment of the MemoryDatabasePlugin which shows thedestroy() method.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    19/93

    19

    19

    Extension/Customization:

    Extending StrutsFramework Classes

    OK. we just took a look at the plug-in mechanism. Now let's see how you canextend Struts framework classes. Again, as was mentioned before, in mostcases, you do not need to extend Framework classes.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    20/93

    20

    20

    Extending Configuration Classes

    ? org.apache.struts.config package contains

    all the classes that are in-memoryrepresentations of all configurationinformation in struts-config.xml file ActionConfig, ActionMapping, ExceptionConfig,

    PluginConfig, MessageResourcesConfig,ControllerConfig, DataSourceConfig,FormBeanConfig, etc

    ? You extend these classes and then specifythe extended class with class nameattribute in struts-config.xml

    Under Struts 1.1, all the configuration information specified in the struts-config.xml file is internally represented by various configuration classes. Andall these classes are in the org.apache.struts.config package. And the aboveslide shows all these configuration classes. And I assume you might be alreadyfamiliar with ActionMapping or FormBeanConfig classes.

    Now you can extend (subclass) these classes and then specify them in theappropriate place in the struts-config.xml file where class file name can bespecified.

    So let's take a look at a few cases where some of these classes can be extendedand then configured.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    21/93

    21

    21

    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

    First, let's take a look at a case where you can extend ActionServlet class. Aswas mentioned before, in Struts 1.0 where there was no plugin mechanism,extending ActionServlet class was a common practice. In Struts 1.1, in whichwe now have plugin mechanism and introduction of RequestProcessor class, it israre that you have to extend ActionServlet class.

    In case you have to, basically the way you can provide your own customizedActionServlet class is to extend the ActionServlet, let's call it myActionServlet,and then configure it in the web.xml as shown above.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    22/93

    22

    22

    Extending RequestProcessor Class

    ? Via element in struts-config.xml

    ? process() method ofRequestProcessorclass iscalled beforeActionForm class is initialized andexecute() method ofAction object get called

    ? Example in struts-cookbook sample code

    RequestProcessor class was introduced in Struts 1.1 and it took over much of thefunctionality that ActionServlet does in Struts 1.0. The process() method ofRequestProcssor class gets called before ActionForm class is initialized andbefore calling execute() method of Action object.

    Since process() method of RequestProcessor class gets called internally byActionServlet, normally, you don't have to worry about this class. Now if youwant to extend it, then you have to do it by explicitly specifying element as mentioned above.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    23/93

    23

    23

    Extending Action Classes

    ? Useful to create a base Action class when

    common logic is shared among manyAction classes

    Create base Action class first then subclass it foractual Action classes

    Now let's see how we can extend Action class. Extending Action class can beuseful when you have to create many Action classes and these Action classesshare common logic. In that case, what you can do is to create a base Actionclass then subclass it for actual Action classes.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    24/93

    24

    24

    Extension/Customization:

    Using MultipleStruts Configuration File

    Now let's talk about how you can use multiple Struts configuration files.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    25/93

    25

    25

    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

    Being able to use multiple Struts configuration files in a multi-developerenvironment is useful since Struts configuration file is no longer a bottleneck.

    Please note that this is a different feature from multiple modules supportwhich we will talk about later on.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    26/93

    26

    26

    web.xml of struts-example

    actionorg.apache.struts.action.ActionServlet

    config

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

    1

    So how do you let Struts framework know that you have multiple con figurationfiles? Basically you provide common separated configuration fikles as .

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    27/93

    27

    27

    struts-config-registration.xml ofstruts-example sample app

  • 7/28/2019 24-StrutsAdvanced_93

    28/93

    28

    28

    struts-config-registration.xml ofstruts-example

    This slide shows element.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    29/93

    29

    29

    ForwardAction

    N ow let's talk about how to extend and customize Strutsframework especially plugin mechanism. We are talking aboutthis topic first because the plugin mechanism is going to be usedby Validator and Tiles frameworks.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    30/93

    30

    30

    Why ForwardAction?

    ? If you have the case where you don't need to

    perform 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 empty

    Action classes? You don't have to create an Action class

    All you have to do is to declaratively configure anAction mapping in your Struts configuration file.

    There are probably many cases in your application where you want an Action tojust forward to a JSP. In fact, the previous tip stated that it's good practice toalways front a JSP with an Action. If you have the case where you don't need toperform any logic in the Action but would like to follow the convention ofgoing through an Action to access a JSP, the ForwardAction can save you fromcreating many empty Action classes. The benefit of the ForwardAction is thatyou don't have to create an Action class of your own. All you have to do is to

    declaratively configure an Action mapping in your Struts configuration file.

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    31/93

    31

    31

    Example: ForwardAction

    ? Suppose that you had a JSP page called

    index.jsp and instead of calling this pagedirectly, you would rather have the applicationgo through an Action class

    ? http://hostname/appname/home.do

    For example, suppose that you had a JSP called index.jsp and instead of callingthis page directly, you would rather have the application go through an Actionclass. What you can do is set up an Action mapping like this:

    When the home action is invoked, the ForwardAction performs a forward to the

    index.jsp page.

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    32/93

    32

    32

    Example: ForwardAction

    ? Another way for forwarding

    While we are discussing forwarding without having to provide an Action class,it should also be mentioned that you could also use the forward attribute of the element to achieve the same behavior. The element wouldlook like this:

    Both approaches save you time and help to reduce the number of files needed

    by an application.

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    33/93

    33

    33

    Why ForwardAction?

    ? You can also prevent direct access to a

    JSP page Move your JSP page under /WEB-INF

    Use ForwardAction

    Another reason you might want to ue ForwardAction is to prevent direct accessto a JSP page by an end-user mostly due to security reasons. You can move theJSP page under WEB-INF directory and then use ForwardAction. Please notethat anything under WEB-INF directory cannot be directly addressable by anend-user.

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    34/93

    34

    34

    Why ForwardAction?? Aligned with Model 2 MVC design pattern

    ? If you are using , you are not usingModel 2 MVC (dispatching is done inside JSPpage)Top page

    ? If you are using ForwardAction, you are using

    Model 2 MVC

    .

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    35/93

    35

    35

    DispatchAction

    N ow let's talk about how to extend and customize Strutsframework especially plugin mechanism. We are talking aboutthis topic first because the plugin mechanism is going to be usedby Validator and Tiles frameworks.

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    36/93

    36

    36

    Why DispatchAction?

    ? To allow multiple related operations to

    reside 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 common

    business logic

    What is the motivation of using DispatchAction class? DispatchAction classallows mutliple related operations to reside in a single Action class instead ofbeing spread over multiple Action classes. It also allows common logic to beshared among these operations since these related operations typically sharesome common business logic.

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    37/93

    37

    37

    How to use DispatchAction?

    ? Create a class that extends DispatchAction

    (instead ofAction)? In a new class, add a method for every

    function 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

    So how do you use DispatchAction? First you create a class that extendsDispatchAction class and then add a method for every function you need toperform on the service. These methods should receive same set of parametersand types as a typical execute() method of an Action class. And because execute()method is provided by the DispatchAction class itself, you should not overridethe execuite() method. Finally you would need an entry to the struts-config.xmlfile.

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    38/93

    38

    38

    Example: ItemAction class extendsDispatchAction

    public 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}

    }}

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    39/93

    39

    39

    Example: struts-config.xml

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

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    40/93

    40

    40

    Example: How To Use it

    ? Using URL: Invoke it using a URL

    ItemAction.do?actionType=addItem? From JSP page

    Save

    Remove

    .

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    41/93

    41

    41

    DeclarativeException Handling

    09/03/2005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    42/93

    42

    42

    Why Declarative Exception Handling?

    ? Previously (Struts 1.0), Action class has to

    deal with all business logic exceptions itself No common exception handling

    Rather difficult to implement

    09/03/ 005

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    43/93

    43

    43

    What is Declarative Exception Handling?

    ? Exception handling policy is declaratively

    specified 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 ...

    / /

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    44/93

    44

    44

    Example in struts-example

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    45/93

    45

    45

    How Does it Work?

    ? When an Exception is thrown inside execute()ofActionclass, 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

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    46/93

    46

    46

    Example in struts-example1

    public ActionForwardexecute

    (ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response)

    throws Exception {

    ...

    throw new PasswordExpiredException(...);

    ...

    }

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    47/93

    47

    47

    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;

    To install your customized exception handler, the first step is to create a class thatextends org.apache.struts.action.ExceptionHandler. There are two methods that you

    can override, execute() and storeException(). In most cases, however, you will justneed to override the execute() method. The signature for the execute() method in theExceptionHandler class is shown here:

    public ActionForward execute( Exception ex,

    ExceptionConfig exConfig,ActionMapping mapping,ActionForm formInstance,HttpServletRequest request,

    HttpServletResponse response) throws ServletException;

    The method takes in several arguments, including the original exception, andreturns an ActionForward object, which directs the controller as to where therequest should be forwarded after the exception is dealt with.

    You can perform whatever behavior you like, but generally you should inspect theexception that was thrown and do something based on the type of exception. Again,the default behavior is to create an error message and forward to the resourcespecified in the configuration file. An example of why you would want or need tocustomize this functionality is to support nested exceptions. Suppose the exception

    contained nested exceptions, and those exceptions also may contain otherexceptions. You would need to override the execute() method to create errormessages for each of these.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    48/93

    48

    48

    Customizing Exception Handling

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

    Once you have created your specialized ExceptionHandler class, you will needto inform the Struts framework to use your version instead of the default Strutsexception handler. To do this, you will just need to declare your class in theStruts configuration file; this is the declarative part.

    You can configure your ExceptionHandler to be used by certain Actionmappings or by all Actions. For specific Action mappings, you include an

    element inside of the element. To utilize theExceptionHandler for all Action mappings, you can specify it inside the element. For example, suppose we want to use a customizedexception handler called CustomizedExceptionHandler for all Action mappings.The element might look like this:

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    49/93

    49

    49

    Customizing Exception Handling

    ? Multiple Custom Exception Handlers

    You can have different exception handlers for different exceptions. In theexample above, the CustomizedExceptionHandler was configured to processany exceptions that were children of java.lang.Exception. However, you cancreate multiple exception handlers, each one worrying about different exceptiontrees. The following XML fragment shows how this can be configured:

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    50/93

    50

    50

    Application Modules

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    51/93

    51

    51

    What are Application Modules?? Allows a single Struts application to be split

    into multiple modules Each module has its own Struts configuration file,

    JSP pages, Actions

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    52/93

    52

    52

    Multiple Application ModuleSupport

    ? Necessary for large scale applications Allows parallel development

    ? Design goals: Support multiple independent Struts configuration

    files 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

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    53/93

    53

    53

    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 tothe 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

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    54/93

    54

    54

    Application Modules:How to configure

    modules

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    55/93

    55

    55

    How to set up and use multipleApplication Modules?

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

    ? Use actions to refer to your pages.

    Very little is required in order to start taking advantage of the Struts applicationmodule feature. Just go through the following steps:

    1. Prepare a config file for each module.2. Inform the controller of your module.3. Use actions to refer to your pages.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    56/93

    56

    56

    Informing the Controller

    ?

    In web.xml...

    config/WEB-INF/conf/struts-default.xml

    config/module1 /WEB-INF/conf/struts-module1.xml

    ...

    In struts 1.0, you listed your configuration file as an initialization parameter to the actionservlet in web.xml. This is still done in 1.1, but it's augmented a little. In order to tell theStruts machinery about your different modules, you specify multiple config initializationparameters, with a slight twist. You'll still use "config" to tell the action servlet about your

    "default" module, however, for each additional module, you will list an initializationparameter named "config/module", where module is the name of your module (this gets usedwhen determining which URIs fall under a given module, so choose something meaningful!).For example:

    ...

    config/WEB-INF/conf/struts-default.xml

    config/module1/WEB-INF/conf/struts-module1.xml

    ...

    This says I have two modules. One happens to be the "default" module, which has no"/module" in it's name, and one named "module1" (config/module1). I've told the controllerit can find their respective configurations under /WEB-INF/conf (which is where I put all myconfiguration files). Pretty simple!

    (My struts-default.xml would be equivalent to what most folks call struts-config.xml. I justlike the symmetry of having all my Struts module files being named struts-.xml)

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    57/93

    57

    57

    Application Modules:How to switch modules

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    58/93

    58

    58

    Methods for Switching Modules

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

    contextRelativeattribute with a value oftrue

    Use the built-inorg.apache.struts.actions.SwitchAction

    There are two basic methods to switching from one module to another. You caneither use a forward (global or local) and specify the contextRelative attribute with avalue of true, or you can use the built-in org.apache.struts.actions.SwitchAction .

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    59/93

    59

    59

    Global Forward...

    ...

    ......

    Here's an example of a global forward:

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    60/93

    60

    60

    Local Forward...

    ......

    ......

    You could do the same thing with a local forward declared in an ActionMapping:

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    61/93

    61

    61

    org.apache.struts.actions.SwitchAction

    ...

    ......

    Finally, you could use org.apache.struts.actions.SwitchAction .

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    62/93

    62

    62

    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=/i

    ndex.do

    There are two basic methods to switching from one module to another. You caneither use a forward (global or local) and specify the contextRelative attribute with avalue of true, or you can use the built-in org.apache.struts.actions.SwitchAction .

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    63/93

    63

    63

    Struts &Security

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    64/93

    64

    64

    Security

    ? 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

    While Struts can work with any approach to user authentication andauthorization, Struts 1.1 and later offers direct support for the standard JavaAuthentication and Authorization Service (JAAS). You can now specify securityroles on an action-by-action basis.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    65/93

    65

    65

    SSL Extension (sslext)

    ? Extension to Struts 1.1

    http://sslext.sourceforge.net

    ? Extends theActionConfig 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

    An extension to Struts 1.1, named sslext, helps solve many of these issues forStruts developers. It extends the ActionConfig class, RequestProcessor, andPlugin classes to define a framework where developers may specify thetransmission protocol behavior for Struts applications. Within the Struts

    configuration file, developers specify which action requests require HTTPStransmission and which should use HTTP. Developers can also specify whether toredirect "improperly-protocoled" requests to the correct protocol.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    66/93

    66

    66

    SSL Extension (sslext)

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

    protocol? and tag extension

    Struts actions specified in either of these tags areanalyzed to determine the protocol that should beused in requesting that action

    The HTML generated by these tags will specify theproper protocol

    Developers can also specify whether to redirect "improperly-protocoled" requeststo the correct protocol.

    In addition to these extensions, the and the tags have

    been extended. In these extensions, the Struts actions specified in either of thesetags are analyzed to determine the protocol that should be used in requesting thataction. The HTML generated by these tags will specify the proper protocol. Anadditional custom tag is defined for allowing users to specify the transmissionprotocol for an individual JSP. This is most often used for form-basedauthentication pages.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    67/93

    67

    67

    Commons:DynaBeans

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    68/93

    68

    68

    COMMONS-BEANUTILS

    ? Pluggable type converters

    ? Mapped properties contact.phone(Work)

    ? DynaBeans Transparently supported by BeanUtils and

    PropertyUtils

    The Bean Introspection Utilities component of the Jakarta Commons subprojectoffers low-level utility classes that assist in getting and setting property values

    on Java classes that follow the naming design patterns outlined in the JavaBeansSpecification, as well as mechanisms for dynamically defining and accessingbean properties.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    69/93

    69

    69

    Commons-Beanutils --DynaBeans

    public 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);

    }

    DynaBeans combine the extensibility of JavaBeans with the flexibility of aMap. Defining even the simplest JavaBean requires defining a new class andcoding a field and two methods for each property. The properties of a DynaBeancan be configured via an XML descriptor. The virtual properties of a DynaBean

    can't be called by standard Java methods, but work well with components thatrely on reflection and introspection.

    In a Struts application, you can use DynaBeans to describe your HTML forms.This strategy can avoid creating a formal JavaBean subclass to store a fewsimple properties.

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    70/93

    70

    70

    Struts Utilities

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    71/93

    71

    71

    Utilities?

    org.apache.struts.util package? Families of classes that solve common

    web app problems.? Suitable for general Java programming

    and are worth checking out? Utilities classes include:

    Beans & Properties Collection Classes JDBC connection pool Message Resources

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    72/93

    72

    72

    Utility Classes

    ? common-*.jar Now required for Struts Might require some package renaming for 1.0.2 Struts

    apps? Many utilities are now located in the Jakarta

    Commons project http://jakarta.apache.org/commons/

    BeanUtils Package org.apache.commons.beanutils

    Collections Package org.apache.commons.collections

    Digester Package org.apache.commons.digester

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    73/93

    73

    73

    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

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    74/93

    74

    74

    XML Parsing

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

    ? Higher level, more developer-friendlyinterface to SAX events

    ? Digester automatically navigates the elementhierarchy of the XML document Element Matching Patterns Processing Rule

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    75/93

    75

    75

    Struts andJ2EE Patterns

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    76/93

    76

    76

    Struts and Core J2EE Patterns

    Client

    Action

    ServletAction

    Action

    Forward

    Action

    FormJSP View

    Request

    Response

    uses

    ControllerModel

    View Helper

    View

    ActionMapping

    (xml)

    Service

    Interface

    Business

    Service

    Business

    Delegate

    Service

    Locator

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    77/93

    77

    77

    Struts and Core J2EE Patterns

    Composite View

    Front Controller Business Delegate

    Compsite Entity

    DataTransfer Object

    Session Facade

    DataTransfer Object

    Presen tation Re qu estCon troll er Create Accou ntDispatch e r UserA ccoun tManage rDe le gate

    EJBSessionBean

    UserAccountManagerEJB

    EJBEntityBeanUserAccountEJB

    EJBEntityBean

    CreditCardEJB

    CreditCardValuesUserAccountValues

    ServerPagetemplate.jsp

    ServerPagemenu.jsp

    JSPInclude

    + themenu.jsp

    ServerPagenew_account.jsp

    ServerPagenew_account_confirm.jsp

    ActionActionServlet

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    78/93

    78

    78

    Nested Tag Library

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    79/93

    79

    79

    The "Nested" Tag Library

    ? Brings a nested context to the functionality of

    the 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 providethe nesting property reference to the Struts system

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    80/93

    80

    80

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

    bean for nested property references

    ? 1:1 correspondence, and identicalfunctionality, of other Struts tags Except the "name" property gets set for you

    automatically ...

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    81/93

    81

    81

    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

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    82/93

    82

    82

    Example: Suppose You WantTo Display the following...

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    83/93

    83

    83

    Example: Using JSTL forIterating Nested Beans

    COMPANY:

    Department:

    Employee:

    E-mail:


    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    84/93

    84

    84

    Example: Using Nested Tag forDoing the Same ThingCOMPANY:

    Department:

    Employee:

    E-mail:

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    85/93

    85

    85

    Example 2:

    ? Before using the nested tags:

    ? After using the nested tags:

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    86/93

    86

    86

    Changes BetweenStruts 1.0 & 1.1

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    87/93

    87

    87

    Struts 1.1 ActionServlet

    ? Introduction of request processor Via RequestProcessorclass

    Handles much of the functionality of ActionServletin Struts1.0

    ? ActionServlet in 1.1 is a thin layer

    Allows developers to customize the requesthandling behavior more easily

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    88/93

    88

    88

    Struts 1.1 Actions

    ? Method perform() replaced by execute() Backwards compatible

    Change necessary to support declarativeexception handling

    ? Addition ofDispatchAction class Supports multiple business methods instead of a

    single execute() method

    Allows easy group of related business methods

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    89/93

    89

    89

    Changes to web.xml andstruts-config.xml? web.xml

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

    Supports a few new parameters

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    90/93

    90

    90

    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 authorization

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    91/93

    91

    91

    Roadmap

    I

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    92/93

    92

    92

    New Features in Struts 1.2

    ? Some deprecations

    ? Validator enhancements? DigestingPlugin added? MappingDispatchAction added

    09/03/2005

  • 7/28/2019 24-StrutsAdvanced_93

    93/93

    93

    93

    Passion!