SlideShare a Scribd company logo
Struts 2

Rajeev Gupta
 M. Tech. CS
Workshop topics

#Introduction & Architecture of
 Struts2                                 # Control tags


#Hello world                             # Date tags

# Action Interface, ActionSupport        # UI tags

 #Aware Interfaces
                                         # Interceptors
 # Namespace, Multiple mapping
 files, Dynamic Method Invocation        # validation framework

 #OGNL,Value Stack
                                         # Struts 2 Type Conversion


                                         #Internationalization (i18n) support

                          Rajeev Gupta        Java Training
#Introduction &
Architecture of Struts2




              Rajeev Gupta   Java Training
Struts2
   Struts2 is Elegant, extensible MVC based framework for
    creating enterprise-ready Java web applications.

             Pull-MVC framework. i.e. the data that is to be displayed to user
              has to be pulled from the Action.

             Supports annotation based configurations

             Action class in Struts 2 act as the model in the web application

             Comes with power APIs to configure Interceptors

             The view part is highly configurable and it supports different
              result-types such as Velocity, FreeMarker, JSP, etc


                               Rajeev Gupta     Java Training
Design Patterns used by struts
•   Front Controller pattern
    –   is a component looks for all the request for specific url pattern
        and routes them into the framework for further processing...


•   Command Pattern
    –   comm. with diff components
    –     Ex Action classes
•   Composite Pattern
    –   struts tiles
•   Decorator Pattern
    –   view solution like freemarker etc


                              Rajeev Gupta   Java Training
STRUTS 2 BASIC ARCHITECTURE
   works as controller
   as per design pattern route all                                  Model
   request to the framework                                         Action
                                                            (Domain Object/Command obj)


                                           takes control of request and act as model
                                           components
                                           action class act as command pattern
                                           communicate with diff class and decide
           Controller                      what result type is to be forwarded...
     FilterDispatcher
                                                                  View
                                                                 RESULT
                                                                    (JSP, AJAX)




                            Rajeev Gupta        Java Training
Struts 1 vs Struts 2 in netshell
•   Struts 1.x
    –   In Struts1.x ActionServlet act as a front controller and for each request new
        form bean instance is created to hold parameter that access an thread of
        Action class
    –   only one instance of Action is created


•   Struts2.x
    –   In Struts2.x FilterDispacher that act as front controller, as request received a
        new instance of action class is created and param interceptor load all the
        parameter from the request to the field of action instance

    –   No separate form bean to hold the request parameter

    –   Create new instance for each and every request ; the action can now hold all the
        request parameter
    –   can be directly mapped to Action (Hence can work as Domain logic...)


                                    Rajeev Gupta       Java Training
Struts 1.x Action

                                    FormBean


     Controller
    ActionServlet

                                         Action




                    Rajeev Gupta   Java Training
Struts 2 Action




       FrontController                                        Action
                                   PARAMS
      FilterDispatcher                                      Form Fields




                         Rajeev Gupta       Java Training
Struts 2 Arch with interceptor
•   Request received by struts framework before it can given to an
    action class. Before action can fire configured interceptor does some
    pre processing
•   Some of interceptor are (detail latter)
       •   Param: responsible for transfer all request parameter to the action instances and
           maintain a copy in values stack...
       •   validation: for validation
       •   Conversion: type conversion
       •   Model driven: for handling form bean
       •   etc
•   after all interceptor execute then ....

•   Action takes responsibilities to execute some business and logic and
    return the result. and decide which Result to be displayed, then this
    display page access value stack with OGNL then response is send
    through interceptor (post processing)

                                     Rajeev Gupta       Java Training
Struts 2 Architecture
  (with Interceptors)
                            Incoming Request                              Response
                                        Params
                                       Validation
Interceptors
                                      Conversion
                                      Model-driven

      OGNL
                     Action             Invoke result              Result
                                                   OGNL


                             ActionContext(ThreadLocal)
                                                       App
               ValueStack      request     session
                                                    context
                                    Rajeev Gupta          Java Training
Advantages of Struts 2
   An Advanced framework with lot of features.
   Based on the MVC Architecture.
   Simple configuration
   Interceptors to reduce the cross cutting functionality
   OGNL
   Pluggable with different Result types like Ajax, JSP,
    Free Marker, Velocity etc.,




                        Rajeev Gupta   Java Training
Struts 2 – Behind the scenes




               Rajeev Gupta   Java Training
Architecture in details
1.   The normal lifecycle of struts begins when the request is sent from client.
     This request is passed to filter dispatcher by web container.


2.   The Filter Dispatcher filter is called which consults the ActionMapper to
     determine whether an Action should be invoked.


3.   If ActionMapper finds an Action to be invoked, the Filter Dispatcher
     delegates control to ActionProxy.


4.   ActionProxy reads the configuration file such as struts.xml. ActionProxy
     creates an instance of ActionInvocation class and delegates the control.


                                Rajeev Gupta      Java Training
Architecture in details…
5.   ActionInvocation is responsible for command pattern implementation. It
     invokes the Interceptors one by one (if required) and then invoke the
     Action.

6.   Once the Action returns, the ActionInvocation is responsible for looking
     up the proper result associated with the Action result code mapped in
     struts.xml.

7.   The Interceptors are executed again in reverse order and the response is
     returned to the Filter (In most cases to FilterDispatcher). And the result is
     then sent to the servlet container which in turns send it back to client.




                               Rajeev Gupta      Java Training
#Hello world




               Rajeev Gupta   Java Training
Struts2 Quick
   Start Downloading and run
   http://struts.apache.org/download.cgi
   Extract struts 2 download
   Struts come with a blank application called struts2-
    blank.war.
   In eclipse import this application
       File Import
       Select WebWar file
       Browse and select the war file
       And Finish leaving the rest default entries.
       Now run this application on the server

                                    Rajeev Gupta       Java Training
Exploring struts2-blank.war

              Some of the important files to
               notice here are
                  struts.xml
                  Some validation xml file
                  Maven
                  lib files
                  some property files
                  java class files
                  web.xml, jsp




Rajeev Gupta         Java Training
Creating hello world application
   Steps
       Create   an dynamic web project in eclipse and put jar in lib( from
        previous project) and set classpath
       set filter in web.xml
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
       Create a hello world Action LoginAction
       Create an struts.xml in src and map action to it
       Create suitable views for displaying result




                              Rajeev Gupta     Java Training
Rajeev Gupta   Java Training
at run time ……




Rajeev Gupta      Java Training
Mapping front controller in web.xml




                                     Mapping filterdispatcher…




               Rajeev Gupta   Java Training
POJO class

                       Action analogous to
                       mini servlet




             Rajeev Gupta    Java Training
Mapping struts.xml




              Rajeev Gupta   Java Training
JSPs to display processing result

                                      Success.jsp




                                       Failure.jsp



               Rajeev Gupta   Java Training
# Action Interface, ActionSupport




             Rajeev Gupta   Java Training
Action Interface
   Action interface define some useful constants, we can
    used these constant as return from action methods.

        public interface Action {
          public static final String SUCCESS = "success";
          public static final String NONE = "none";
          public static final String ERROR = "error";
          public static final String INPUT = "input";
          public static final String LOGIN = "login";
          public String execute() throws Exception;
        }




                                Rajeev Gupta       Java Training
Action Interface
   static final String SUCCESS
       Indicates successful execution and that means the result view is shown to the end user.
   static final String ERROR
       Indicates that there was a failure.
       Show an error view, possibly asking the user to retry entering data
   static final String INPUT
       This is used for a form action indicating that inputs are. The form associated with the handler should
        be shown to the end user.
       This result is also used if the given input params are invalid, meaning the user should try providing input
        again.
   static final String LOGIN
       Indicates that the user was not logged in.
       The login view should be shown.
   static final String NONE
       Indicates successful execution but no action is taken.
       Useful for actions which wants to redirect etc.




                                              Rajeev Gupta          Java Training
ActionSupport
   ActionSupport class provides default implementaion for
    various services required by common actions classes...

class ActionSupport implements Validateable,
ValidationAware,LocaleProvider,TextProvider,ValidationAware,Action,Serilizable{
}




                                 Rajeev Gupta     Java Training
ActionSupport
   <<Validateable>>:
     provide validate() method that allows our action is to be validate
      validate() called before execute() method

   <<LocaleProvider>>
     getLocale() method to provide locate to be used for localized methods


   <<ValidationAware>>
     provides methods for saving/retrieving errors messages
       void addActionError(String message);
       void addFieldError(String fieldName, String message);




                               Rajeev Gupta     Java Training
ActionSupport
   <<TextProvider>>
       provides methods to access to resoure bundles
           Ex:
           String getText(String key, String val);


   <<Serializable>>
       marker interface.......

   Use of ActionSupport class for <<Validateable>>and <<TextProvider>>and
    property file
   Next we write login application with validation and
    ApplicationResources.properties file

                                    Rajeev Gupta      Java Training
Modified Login Application
                      We write key-value pair in
                       ApplicationResources.properties file
                      Note that key= “…..” will pick values
                       form .property file….
                      Loose coupling and internationalization can be
                       provide in this way
                   




               Rajeev Gupta       Java Training
Modified Login Application

                                 Have validate() in action
                                  class……..




                                 Have property file




                                 Mapping for “input” in
                                  struts.xml

               Rajeev Gupta   Java Training
Modified Login Application
   Order of execution of action is as follows:
       If action implements validateable interface , action validate()
        method is going to execute before execute() method it return
        “input” if validation fail.




                             Rajeev Gupta   Java Training
ActionContext
   ActionContext can be define as container, which contain objects that
    require Action for its execution

   We can use ActionContext to get object like request,
    response,session,parameter etc




   Although we have better technique to get session, reqest
    etc that we are going to discuss next topic.

                               Rajeev Gupta    Java Training
#Aware Interfaces




             Rajeev Gupta   Java Training
Aware Interface
   Aware interface provides aka. Dependency Injection in Struts2
   When we want HTTP specific object in action, we can use aware interface to inject
    dependancies….
    <<ApplicationAware>>
      public void setApplication(Map app);
    <<SessionAware>>
      public void setSession(Map session);
    <<ParameterAware>>
      public void setParameter(Map param);
    <<ServletResponseAware>>
      public void setervletResponseAware(HttpServletResponse res);
    <<ServletRequestAware>>
      public void setervletResponseAware(HttpServletRequest res)


                                  Rajeev Gupta     Java Training
Ex: Setting something in session scope




   Now accessing session scoped variable in JSP

Simlirly.....
         <s:property value="#session.user"/>
         <s:property value="#session['user']"/>


         <s:property value="#application.user"/>
         <s:property value="#parameters.user"/>
                                     Rajeev Gupta   Java Training
More about Struts 2 Actions classes
   Primary job of actions
       Action act as a data carrier (DTO)
       Action also working as controller (As in simple Servlet
        application)
       We should not write business logic in action rather we should
        call DAO form it.
   How action POJO works
         First, the
                   action plays an important role in the transfer of data from
          the request through to the view, whether its a JSP or other type of
          result.
         Second, the action assist the framework in determining which result
          should render the view that will be returned in the response to the
          request.

                                Rajeev Gupta    Java Training
More about Struts 2 Actions classes
   Condition to be an action

       The only requirement for actions in Struts2 is that there must
        be one no-argument method that returns either a String or
        Result object and must be a POJO.

       If the no-argument method is not specified, the default
        behaviour is to use the execute() method.

       Optionally you can extend the ActionSupport class which
        implements six interfaces including <<Action>> interface


                             Rajeev Gupta   Java Training
# Namespace, Multiple mapping files,
Dynamic Method Invocation




              Rajeev Gupta   Java Training
Namespace
   Note that package tag(struts.xml) has the following
    attributes:
          Attribute               Description
          name (required)         The unique identifier for the package

          extends                 Which package does this package extend from?
                                  By default, we use struts-default as the base package.

          abstract                If marked true, the package is not available for end
                                  user consumption.


          namesapce               Unique namespace for the actions




                            Rajeev Gupta        Java Training
Struts 2 Namespace

   Namespace is a concept to handle the multiple modules by
    given a namespace to each module.
   In addition, it can used to avoid conflicts between same action
    names located at different modules




                           Rajeev Gupta   Java Training
The package
                       “name” will not
                       affect the result,
                       just give a
                       meaningful name.




Rajeev Gupta   Java Training
Struts 2 action
                               namespace
                               map to folder
                               structure.




Rajeev Gupta   Java Training
Mapping how it works?




              Rajeev Gupta   Java Training
Mapping how it works?




              Rajeev Gupta   Java Training
Multiple Struts configuration files
   In Struts 2, we should always assign each module a struts configuration file.
   Lets assume that we have two application modules user and audit, In this case, we
    can create three files :
        struts-audit.xml – Put all audit module settings here.
        struts-user.xml – Put all user modules settings here.
        struts.xml – Put default settings and include the struts-audit.xml and struts-
          user.xml.




                                     Rajeev Gupta       Java Training
Rajeev Gupta   Java Training
Dynamic Method Invocation
   It help us to avoid configuring a separate action mapping for each method in the
    Action class by using the wildcard method


   AKA short cut can create problems




                                            The word that matches for the first
                                            asterisk will be substituted for the method
                                            attribute. So when the request URL is
                                            "addUser" the add() method in the
                                            UserAction class will be invoked.


                                  Rajeev Gupta       Java Training
Dynamic Method Invocation:
Action class




              Rajeev Gupta   Java Training
#OGNL, Value Stack




            Rajeev Gupta   Java Training
OGNL 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




                               Rajeev Gupta    Java Training
Struts 2 and OGNL

                               The automation of data transfer and type
                                conversion is one of the most powerful
                                features of Struts 2. With the help of
                                OGNL, the Struts 2 framework allows
                                transfer of data onto more complex Java-
                                side types like List, Map, etc.


                               OGNL is the interface between the
                                Struts 2 framework string-based HTTP
                                Input and Output and the Java-based
                                internal processing.




             Rajeev Gupta        Java Training
Rajeev Gupta   Java Training
can get valueStack object inside your
action as follows



                      Rajeev Gupta   Java Training
Once you have a
                               ValueStack
                               object, you can
                               use following
                               methods to
                               manipulate that
                               object




Rajeev Gupta   Java Training
Rajeev Gupta   Java Training
Rajeev Gupta   Java Training
# Control tags




                 Rajeev Gupta   Java Training
Generic tags
   Struts2 tags are divided into generic and UI tags

       Generic tags
           Used for controlling flow of data
           And for data extraction from the value stack.

               There are two type of generic tags
                   Control tags
                   Data tags
       UI tags
           Concern about form creation




                                     Rajeev Gupta    Java Training
Control tags
if                                    iterator
                                                A kind of for loop to iterate for collection array etc
       <s:if test="%{true}">
       this line will be displayed.             Ex:
       </s:if>                                  <s:iterator status="stat“ value="{11,22,33,44,55,66}">
                                                       <s:property value="#stat.index"/>
       <s:if test="%{false}">                          <s:property value="top"/>
       this line will be displayed.                    <s:if test="#stat.last==false">,</s:if>
                                                </s:iterator>
       </s:if>

else
       <s:if test="type=="manager">
             your are an manager
       </s:if>
       <s:else>
                 not an manager
       </s:if>




                                      Rajeev Gupta         Java Training
Control tags
append
             used to append collection objects to an single collection
             <s:append id="myAppender">
                           <s:param value="%{fruits}"/>
                           <s:param value="%{books}"/>
                           <s:param value="%{colors}"/>
             </s:append>
             Now:
             <s:iterator value="%{#myAppender}">
             </s:iterator>


   So many tags, explore yourself
   merge
   sort
   subset
   generator
   elseIf
                                            Rajeev Gupta           Java Training
Control tags
   Setting values in an action




   How to display in an view:




                       Rajeev Gupta   Java Training
#Data Tags




             Rajeev Gupta   Java Training
Data tags
   Data tags primary used for creating and manipulating data
   helps to access data from value stack or help to put data
    to value stack

   Examples

a
    Similer to <a href..../>
           Ex:
           <s:url id="url" action="addAction"></s:url>
           <s:a href="%{url}">adding</s:a>


                                  Rajeev Gupta      Java Training
Data tags
action
     Used to call actions direcly from jsp


     Ex: consider following in struts.xml


     <action name="regForm" class="com.RegistrationAction">
                     <result name="success">reg.jsp</result>
     </action>




     Now:
     in an jsp....




     <s:action name="regForm" executeResult="true"/>


                                   by default it is false




                                            Rajeev Gupta       Java Training
Data tags
push
                used to push the value on value stack

                id : used for referencing element
                value: specify value to be pushed to value stack
                make accessing data simple...use if you have to
                use that data object extensively....


    Example :
    Consider below example , how use of push make easy to access session scoped varaibles….


<s:set name="user" value="#session['user']"/>


<s:push value="#user"/>
    <s:property value="userName'/>
    ....
    <s:property value="address"/>
</s:push>



                                                        Rajeev Gupta           Java Training
Data tags
calling an action from href
<p><a href="<s:url action='hello'/>">Hello World</a></p>


mapping of that action
<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction"
   method="execute">
 <result name="success">/HelloWorld.jsp</result>
</action>


url tag with param


<s:url action="hello" var="helloLink">
 <s:param name="userName">Bruce Phillips</s:param>
</s:url>


<p><a href="${helloLink}">Hello Bruce Phillips</a></p>
                                     Rajeev Gupta        Java Training
Data tags
date
          <s:date name="new java.util.Date()" format="dd/mmm/yyyy"/>
          <s:date name="new java.util.Date()" format="%{getText('app.date.format')}"/>


include
          <s:include value="header.jsp"/>




Lots of tags: please explore 
Bean                 set       text
url                  property debug
18n etc…



                                    Rajeev Gupta        Java Training
# UI tags




            Rajeev Gupta   Java Training
UI tags
   form
                                         Label
   checkboxlist
                                         Hidden
   file
                                         Doubleselect
   token
                                         Combobox
   password
                                         Submit
   textarea
                                         Datetimepicker
   checkbox
                                         Optgroup
   select
                                         textfield
   radio
   head
   optiontransferselect
   reset
   updownselect


                           Rajeev Gupta        Java Training
UI tags




   Please refer examples shared…

                       Rajeev Gupta   Java Training
# Interceptors




             Rajeev Gupta   Java Training
Interceptors

    Can execute code before and after execution
    Are thread-safe
    Can be used for
       Validation
       Pre populating fields
       Double-submit prevention
       Session control
       Authentication
       Type conversion




                                Rajeev Gupta       Java Training
Interceptors
   Interceptors allow for crosscutting functionality to be implemented separately
    from the action as well as the framework.
   AOP ie Aspect oriented programming is not the replacement of OOP but it is
    support concept to oops
   Interceptors are conceptually the same as servlet filters.


    You can achieve the following using interceptors:


       Providing preprocessing logic before the action is called.
       Providing postprocessing logic after the action is called.
       Catching exceptions so that alternate processing can be performed.



Many of the features provided in the Struts2 framework are implemented using
  interceptors
                                   Rajeev Gupta       Java Training
Interceptors
•   Struts2 comes with default list of Interceptors already configured in
    the application in struts-default.xml file. We can create our own
    custom Interceptors and plugin into a Struts2 based web application.

•   Framework creates an object of ActionInvocation that
    encapsulates the action and all the interceptors configured for that
    action.

•   Each interceptors are called before the action gets called. Once the
    action is called and result is generated, each interceptors are again
    called in reverse order to perform post processing work.

•   Interceptors can alter the workflow of action. It may prevent the
    execution of action.

                             Rajeev Gupta    Java Training
Interceptors
   Interceptor examples include:
       exception handling,
       file uploading,
       lifecycle callbacks and
       validation etc.


   In fact, as Struts2 bases much of its functionality on
    interceptors, it is not unlikely to have 7 or 8 interceptors
    assigned per action.



                                  Rajeev Gupta   Java Training
Some Interceptors in Struts 2(I)
   Alias
     Allows parameters to have different name aliases across
      requests.
   checkbox
     Assists in managing check boxes by adding a parameter
     value of false for check boxes that are not checked.
    conversionError
     Places error information from converting strings to
      parameter types into the action's field errors.
   createSession
     Automatically creates an HTTP session if one does not
      already exist
                          Rajeev Gupta   Java Training
Some Interceptors in Struts 2 (II)
   Debugging
       Provides several different debugging screens to the developer.
   execAndWait
       Sends the user to an intermediary waiting page while the action executes in the
        background.
   Exception
       Maps exceptions that are thrown from an action to a result, allowing automatic exception
        handling via redirection.


   fileUpload
       Facilitates easy file uploading.
   i18n
       Keeps track of the selected locale during a user's session.
   logger
       Provides simple logging by outputting the name of the action being executed.

                                           Rajeev Gupta      Java Training
Some Interceptors in Struts 2 (III)
   Params
     Sets the request parameters on the action.
    prepare
     This is typically used to do pre-processing work, such as
      setup database connections.
   Profile
     Allows simple profiling information to be logged for actions.
   Scope
     Stores and retrieves the action's state in the session or
      application scope.



                           Rajeev Gupta   Java Training
Some Interceptors in Struts 2 (IV)
   ServletConfig
       Provides the action with access to various servlet-based
        information.
   timer
       Provides simple profiling information in the form of how long
        the action takes to execute.
   Token
       Checks the action for a valid token to prevent duplicate form
        submission.
   Validation
       Provides validation support for actions

                             Rajeev Gupta   Java Training
Interceptors
   How to use Interceptors?
       Interceptor need to be configure in struts.xml file as

        <interceptor-ref name="params"/>
        <interceptor-ref name="timer" />




                              Rajeev Gupta   Java Training
Rajeev Gupta   Java Training
Mapping interceptor to actions




               Rajeev Gupta   Java Training
Important to note…




              Rajeev Gupta   Java Training
Custom interceptor
   Steps
            1.   Create a class that implements Interceptor.
                 and Implement the intercept(ActionInvocation invocation)
                 method.
            2.   Configure the interceptor in the struts.xml and Link it to action.




                               Rajeev Gupta      Java Training
Step 1:

                                         Create a class that
                                         implements
                                         com.opensymphony.xwork
                                         2.interceptor.Interceptor.




                                            Implement the
                                            intercept(ActionInvoca
                                            tion invocation)




                            This is the method responsible for
                            calling the next interceptor or the
                            action
          Rajeev Gupta   Java Training
Rajeev Gupta   Java Training
Step 2:




                          Configure the interceptor in the
                          struts.xml and Link it to
                          action.




          Rajeev Gupta   Java Training
Interceptor will execute…




               Rajeev Gupta   Java Training
# validation framework




              Rajeev Gupta   Java Training
Validation
   2 ways to do validation
    1.   with the help of ActionSupport
    2.   XML way, more flexible




                           Rajeev Gupta   Java Training
Validation with with the help of
ActionSupport
   Steps
    Create an form




    Add validate() method to action class…




                          Rajeev Gupta   Java Training
Validation with with the help of
ActionSupport
   Don’t forget to map for “input” in strut.xml




   When the user presses the submit button, Struts 2 will automatically execute the
    validate method and if any of the if statements listed inside the method are true,
    Struts 2 will call its addFieldError method. If any errors have been added then Struts
    2 will not proceed to call the execute method. Rather the Struts 2 framework will
    return input as the result of calling the action.


   So when validation fails and Struts 2 returns input, the Struts 2 framework will
    redisplay the index.jsp file.
                                   Rajeev Gupta       Java Training
Struts - XML Based validation
   More flexible and powerful.
   Steps
    1.   Create registration form




    2.   Create Action class say EmployeeReg




                            Rajeev Gupta   Java Training
Struts - XML Based validation
                             3. Now create EmployeeReg-
                                   validation.xml validation file in
                                   same package in which
                                   EmployeeReg is stored.

                                If the action EmployeeReg then
                                 name of validation file must be
                                 EmployeeReg-validation.xml
                                      create validation xml file in
                                        '[action-class]'-validation.xml

                                If we want Client side
                                 validation
                                Just add validate="true“ to <s:form…> this
                                 option let java script produce at client
                                 side……


              Rajeev Gupta          Java Training
Struts-XML based validation
   Refer given code…






                        Rajeev Gupta   Java Training
# Struts 2 Type Conversion




             Rajeev Gupta   Java Training
Struts 2 Type Conversion
   Struts2 provide automatically type conversion for basic
    data types such as ....
           Integer, Float, Double, Decimal
           Date and Datetime
           Arrays and Collections
           Enumerations
           Boolean
           BigDecimal
   What if we have user define object?
       In that cases Struts 2 Type Conversion is very handy.....




                                  Rajeev Gupta   Java Training
# Internationalization (i18n) support




              Rajeev Gupta   Java Training
Internationalization
   For implement i18n in we need

      1. resource bundles
      2. interceptors and
      3. tag libraries
   Hello world example (Refer code Provided)




                            Rajeev Gupta   Java Training
Internationalization
   We need not to worry about writing pages in different languages. All we
    have to do is to create a resource bundle for each language that you want.

   The resource bundles will contain titles, messages, and other text in the
    language of your user.

   Resource bundles are the file that contains the key/value pairs for the
    default language of your application.

   To develop your application in multiple languages, you would have to
    maintain multiple property files corresponding to those languages/locale
    and define all the content in terms of key/value    pairs.



                                Rajeev Gupta     Java Training
Internationalization
   For example if you are going to develop your application
    for US English (Default), Spanish, and Franch the you
    would have to create three properties files.
    global.properties
       global.properties: By default English (United States) will be applied
       global_fr.properties: This will be used for Franch locale.
       global_es.properties: This will be used for Spanish locale.




                                 Rajeev Gupta       Java Training
Rajeev Gupta   Java Training

More Related Content

PPTX
Spring boot
PPTX
Java 8 Lambda and Streams
PDF
Spring Framework - Core
PPTX
Spring data jpa
PPT
Hibernate
PDF
Spring boot jpa
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
PDF
PUC SE Day 2019 - SpringBoot
Spring boot
Java 8 Lambda and Streams
Spring Framework - Core
Spring data jpa
Hibernate
Spring boot jpa
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
PUC SE Day 2019 - SpringBoot

What's hot (20)

PPTX
Spring boot - an introduction
PPT
Hibernate architecture
PPTX
Spring framework IOC and Dependency Injection
PPTX
Spring Boot
PDF
Spring Data JPA
PDF
Spring Boot
PPT
Spring Boot in Action
PPTX
PPTX
Java Lambda Expressions.pptx
PDF
Hibernate Presentation
PPTX
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
PPTX
Apache tomcat
PDF
Spring MVC Framework
ODP
Testing RESTful Webservices using the REST-assured framework
PDF
Java 8 Lambda Expressions
PPTX
Springboot Microservices
PPTX
Spring boot
PDF
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
PPTX
Java Spring Framework
PPTX
Spring & hibernate
Spring boot - an introduction
Hibernate architecture
Spring framework IOC and Dependency Injection
Spring Boot
Spring Data JPA
Spring Boot
Spring Boot in Action
Java Lambda Expressions.pptx
Hibernate Presentation
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Apache tomcat
Spring MVC Framework
Testing RESTful Webservices using the REST-assured framework
Java 8 Lambda Expressions
Springboot Microservices
Spring boot
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Java Spring Framework
Spring & hibernate
Ad

Viewers also liked (6)

PPTX
01 introduction to struts2
PPT
Struts2
PDF
Struts2 notes
PPT
Struts(mrsurwar) ppt
PDF
Lecture 8 monitoring & controlling (1)
PPT
Struts Ppt 1
01 introduction to struts2
Struts2
Struts2 notes
Struts(mrsurwar) ppt
Lecture 8 monitoring & controlling (1)
Struts Ppt 1
Ad

Similar to Struts2 (20)

PDF
important struts interview questions
PPT
PPTX
Apache Struts 2 Framework
PPTX
Skillwise Struts.x
PPTX
Struts 1
PPT
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
PPTX
PPT
Struts 2-overview2
PPT
Struts2.x
PDF
Struts2
DOCX
Struts notes
PDF
Struts Basics
PPT
strut2
PDF
Struts 2 In Action 1st Edition Don Brown Chad Michael Davis Scott Stanlick
PPT
Struts 2 Overview
PDF
Introduction to struts
PPT
Struts 2-overview2
PPT
Struts Overview
PDF
Struts2 - 101
PDF
Web Development with Apache Struts 2
important struts interview questions
Apache Struts 2 Framework
Skillwise Struts.x
Struts 1
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Struts 2-overview2
Struts2.x
Struts2
Struts notes
Struts Basics
strut2
Struts 2 In Action 1st Edition Don Brown Chad Michael Davis Scott Stanlick
Struts 2 Overview
Introduction to struts
Struts 2-overview2
Struts Overview
Struts2 - 101
Web Development with Apache Struts 2

More from Rajiv Gupta (17)

PDF
Spring5 hibernate5 security5 lab step by step
PDF
GOF Design pattern with java
PPTX
1. java script language fundamentals
PDF
Introduction to jsf2
PDF
Hibernate 3
PDF
Weblogic 11g admin basic with screencast
PDF
jsf2 Notes
PDF
Java 7
PDF
Lab work servlets and jsp
PPT
Java Servlet
PDF
Spring aop with aspect j
PDF
Spring 3.0 dependancy injection
PDF
Java spring framework
TXT
Jsp Notes
PDF
Java Logging discussion Log4j,Slf4j
TXT
Advance C++notes
PDF
Core java 5 days workshop stuff
Spring5 hibernate5 security5 lab step by step
GOF Design pattern with java
1. java script language fundamentals
Introduction to jsf2
Hibernate 3
Weblogic 11g admin basic with screencast
jsf2 Notes
Java 7
Lab work servlets and jsp
Java Servlet
Spring aop with aspect j
Spring 3.0 dependancy injection
Java spring framework
Jsp Notes
Java Logging discussion Log4j,Slf4j
Advance C++notes
Core java 5 days workshop stuff

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Modernizing your data center with Dell and AMD
PDF
Approach and Philosophy of On baking technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Modernizing your data center with Dell and AMD
Approach and Philosophy of On baking technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Monthly Chronicles - July 2025
The Rise and Fall of 3GPP – Time for a Sabbatical?
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Digital-Transformation-Roadmap-for-Companies.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Mobile App Security Testing_ A Comprehensive Guide.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Encapsulation theory and applications.pdf
Electronic commerce courselecture one. Pdf
Chapter 3 Spatial Domain Image Processing.pdf
20250228 LYD VKU AI Blended-Learning.pptx

Struts2

  • 1. Struts 2 Rajeev Gupta M. Tech. CS
  • 2. Workshop topics #Introduction & Architecture of Struts2 # Control tags #Hello world # Date tags # Action Interface, ActionSupport # UI tags #Aware Interfaces # Interceptors # Namespace, Multiple mapping files, Dynamic Method Invocation # validation framework #OGNL,Value Stack # Struts 2 Type Conversion #Internationalization (i18n) support Rajeev Gupta Java Training
  • 3. #Introduction & Architecture of Struts2 Rajeev Gupta Java Training
  • 4. Struts2  Struts2 is Elegant, extensible MVC based framework for creating enterprise-ready Java web applications.  Pull-MVC framework. i.e. the data that is to be displayed to user has to be pulled from the Action.  Supports annotation based configurations  Action class in Struts 2 act as the model in the web application  Comes with power APIs to configure Interceptors  The view part is highly configurable and it supports different result-types such as Velocity, FreeMarker, JSP, etc Rajeev Gupta Java Training
  • 5. Design Patterns used by struts • Front Controller pattern – is a component looks for all the request for specific url pattern and routes them into the framework for further processing... • Command Pattern – comm. with diff components – Ex Action classes • Composite Pattern – struts tiles • Decorator Pattern – view solution like freemarker etc Rajeev Gupta Java Training
  • 6. STRUTS 2 BASIC ARCHITECTURE works as controller as per design pattern route all Model request to the framework Action (Domain Object/Command obj) takes control of request and act as model components action class act as command pattern communicate with diff class and decide Controller what result type is to be forwarded... FilterDispatcher View RESULT (JSP, AJAX) Rajeev Gupta Java Training
  • 7. Struts 1 vs Struts 2 in netshell • Struts 1.x – In Struts1.x ActionServlet act as a front controller and for each request new form bean instance is created to hold parameter that access an thread of Action class – only one instance of Action is created • Struts2.x – In Struts2.x FilterDispacher that act as front controller, as request received a new instance of action class is created and param interceptor load all the parameter from the request to the field of action instance – No separate form bean to hold the request parameter – Create new instance for each and every request ; the action can now hold all the request parameter – can be directly mapped to Action (Hence can work as Domain logic...) Rajeev Gupta Java Training
  • 8. Struts 1.x Action FormBean Controller ActionServlet Action Rajeev Gupta Java Training
  • 9. Struts 2 Action FrontController Action PARAMS FilterDispatcher Form Fields Rajeev Gupta Java Training
  • 10. Struts 2 Arch with interceptor • Request received by struts framework before it can given to an action class. Before action can fire configured interceptor does some pre processing • Some of interceptor are (detail latter) • Param: responsible for transfer all request parameter to the action instances and maintain a copy in values stack... • validation: for validation • Conversion: type conversion • Model driven: for handling form bean • etc • after all interceptor execute then .... • Action takes responsibilities to execute some business and logic and return the result. and decide which Result to be displayed, then this display page access value stack with OGNL then response is send through interceptor (post processing) Rajeev Gupta Java Training
  • 11. Struts 2 Architecture (with Interceptors) Incoming Request Response Params Validation Interceptors Conversion Model-driven OGNL Action Invoke result Result OGNL ActionContext(ThreadLocal) App ValueStack request session context Rajeev Gupta Java Training
  • 12. Advantages of Struts 2  An Advanced framework with lot of features.  Based on the MVC Architecture.  Simple configuration  Interceptors to reduce the cross cutting functionality  OGNL  Pluggable with different Result types like Ajax, JSP, Free Marker, Velocity etc., Rajeev Gupta Java Training
  • 13. Struts 2 – Behind the scenes Rajeev Gupta Java Training
  • 14. Architecture in details 1. The normal lifecycle of struts begins when the request is sent from client. This request is passed to filter dispatcher by web container. 2. The Filter Dispatcher filter is called which consults the ActionMapper to determine whether an Action should be invoked. 3. If ActionMapper finds an Action to be invoked, the Filter Dispatcher delegates control to ActionProxy. 4. ActionProxy reads the configuration file such as struts.xml. ActionProxy creates an instance of ActionInvocation class and delegates the control. Rajeev Gupta Java Training
  • 15. Architecture in details… 5. ActionInvocation is responsible for command pattern implementation. It invokes the Interceptors one by one (if required) and then invoke the Action. 6. Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. 7. The Interceptors are executed again in reverse order and the response is returned to the Filter (In most cases to FilterDispatcher). And the result is then sent to the servlet container which in turns send it back to client. Rajeev Gupta Java Training
  • 16. #Hello world Rajeev Gupta Java Training
  • 17. Struts2 Quick  Start Downloading and run  http://struts.apache.org/download.cgi  Extract struts 2 download  Struts come with a blank application called struts2- blank.war.  In eclipse import this application  File Import  Select WebWar file  Browse and select the war file  And Finish leaving the rest default entries.  Now run this application on the server Rajeev Gupta Java Training
  • 18. Exploring struts2-blank.war  Some of the important files to notice here are  struts.xml  Some validation xml file  Maven  lib files  some property files  java class files  web.xml, jsp Rajeev Gupta Java Training
  • 19. Creating hello world application  Steps  Create an dynamic web project in eclipse and put jar in lib( from previous project) and set classpath  set filter in web.xml org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  Create a hello world Action LoginAction  Create an struts.xml in src and map action to it  Create suitable views for displaying result Rajeev Gupta Java Training
  • 20. Rajeev Gupta Java Training
  • 21. at run time …… Rajeev Gupta Java Training
  • 22. Mapping front controller in web.xml Mapping filterdispatcher… Rajeev Gupta Java Training
  • 23. POJO class Action analogous to mini servlet Rajeev Gupta Java Training
  • 24. Mapping struts.xml Rajeev Gupta Java Training
  • 25. JSPs to display processing result Success.jsp Failure.jsp Rajeev Gupta Java Training
  • 26. # Action Interface, ActionSupport Rajeev Gupta Java Training
  • 27. Action Interface  Action interface define some useful constants, we can used these constant as return from action methods. public interface Action { public static final String SUCCESS = "success"; public static final String NONE = "none"; public static final String ERROR = "error"; public static final String INPUT = "input"; public static final String LOGIN = "login"; public String execute() throws Exception; } Rajeev Gupta Java Training
  • 28. Action Interface  static final String SUCCESS  Indicates successful execution and that means the result view is shown to the end user.  static final String ERROR  Indicates that there was a failure.  Show an error view, possibly asking the user to retry entering data  static final String INPUT  This is used for a form action indicating that inputs are. The form associated with the handler should be shown to the end user.  This result is also used if the given input params are invalid, meaning the user should try providing input again.  static final String LOGIN  Indicates that the user was not logged in.  The login view should be shown.  static final String NONE  Indicates successful execution but no action is taken.  Useful for actions which wants to redirect etc. Rajeev Gupta Java Training
  • 29. ActionSupport  ActionSupport class provides default implementaion for various services required by common actions classes... class ActionSupport implements Validateable, ValidationAware,LocaleProvider,TextProvider,ValidationAware,Action,Serilizable{ } Rajeev Gupta Java Training
  • 30. ActionSupport  <<Validateable>>:  provide validate() method that allows our action is to be validate validate() called before execute() method  <<LocaleProvider>>  getLocale() method to provide locate to be used for localized methods  <<ValidationAware>>  provides methods for saving/retrieving errors messages  void addActionError(String message);  void addFieldError(String fieldName, String message); Rajeev Gupta Java Training
  • 31. ActionSupport  <<TextProvider>>  provides methods to access to resoure bundles  Ex:  String getText(String key, String val);  <<Serializable>>  marker interface.......  Use of ActionSupport class for <<Validateable>>and <<TextProvider>>and property file  Next we write login application with validation and ApplicationResources.properties file Rajeev Gupta Java Training
  • 32. Modified Login Application  We write key-value pair in ApplicationResources.properties file  Note that key= “…..” will pick values form .property file….  Loose coupling and internationalization can be provide in this way  Rajeev Gupta Java Training
  • 33. Modified Login Application  Have validate() in action class……..  Have property file  Mapping for “input” in struts.xml Rajeev Gupta Java Training
  • 34. Modified Login Application  Order of execution of action is as follows:  If action implements validateable interface , action validate() method is going to execute before execute() method it return “input” if validation fail. Rajeev Gupta Java Training
  • 35. ActionContext  ActionContext can be define as container, which contain objects that require Action for its execution  We can use ActionContext to get object like request, response,session,parameter etc  Although we have better technique to get session, reqest etc that we are going to discuss next topic. Rajeev Gupta Java Training
  • 36. #Aware Interfaces Rajeev Gupta Java Training
  • 37. Aware Interface  Aware interface provides aka. Dependency Injection in Struts2  When we want HTTP specific object in action, we can use aware interface to inject dependancies…. <<ApplicationAware>> public void setApplication(Map app); <<SessionAware>> public void setSession(Map session); <<ParameterAware>> public void setParameter(Map param); <<ServletResponseAware>> public void setervletResponseAware(HttpServletResponse res); <<ServletRequestAware>> public void setervletResponseAware(HttpServletRequest res) Rajeev Gupta Java Training
  • 38. Ex: Setting something in session scope  Now accessing session scoped variable in JSP Simlirly..... <s:property value="#session.user"/> <s:property value="#session['user']"/> <s:property value="#application.user"/> <s:property value="#parameters.user"/> Rajeev Gupta Java Training
  • 39. More about Struts 2 Actions classes  Primary job of actions  Action act as a data carrier (DTO)  Action also working as controller (As in simple Servlet application)  We should not write business logic in action rather we should call DAO form it.  How action POJO works  First, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result.  Second, the action assist the framework in determining which result should render the view that will be returned in the response to the request. Rajeev Gupta Java Training
  • 40. More about Struts 2 Actions classes  Condition to be an action  The only requirement for actions in Struts2 is that there must be one no-argument method that returns either a String or Result object and must be a POJO.  If the no-argument method is not specified, the default behaviour is to use the execute() method.  Optionally you can extend the ActionSupport class which implements six interfaces including <<Action>> interface Rajeev Gupta Java Training
  • 41. # Namespace, Multiple mapping files, Dynamic Method Invocation Rajeev Gupta Java Training
  • 42. Namespace  Note that package tag(struts.xml) has the following attributes: Attribute Description name (required) The unique identifier for the package extends Which package does this package extend from? By default, we use struts-default as the base package. abstract If marked true, the package is not available for end user consumption. namesapce Unique namespace for the actions Rajeev Gupta Java Training
  • 43. Struts 2 Namespace  Namespace is a concept to handle the multiple modules by given a namespace to each module.  In addition, it can used to avoid conflicts between same action names located at different modules Rajeev Gupta Java Training
  • 44. The package “name” will not affect the result, just give a meaningful name. Rajeev Gupta Java Training
  • 45. Struts 2 action namespace map to folder structure. Rajeev Gupta Java Training
  • 46. Mapping how it works? Rajeev Gupta Java Training
  • 47. Mapping how it works? Rajeev Gupta Java Training
  • 48. Multiple Struts configuration files  In Struts 2, we should always assign each module a struts configuration file.  Lets assume that we have two application modules user and audit, In this case, we can create three files :  struts-audit.xml – Put all audit module settings here.  struts-user.xml – Put all user modules settings here.  struts.xml – Put default settings and include the struts-audit.xml and struts- user.xml. Rajeev Gupta Java Training
  • 49. Rajeev Gupta Java Training
  • 50. Dynamic Method Invocation  It help us to avoid configuring a separate action mapping for each method in the Action class by using the wildcard method  AKA short cut can create problems The word that matches for the first asterisk will be substituted for the method attribute. So when the request URL is "addUser" the add() method in the UserAction class will be invoked. Rajeev Gupta Java Training
  • 51. Dynamic Method Invocation: Action class Rajeev Gupta Java Training
  • 52. #OGNL, Value Stack Rajeev Gupta Java Training
  • 53. OGNL 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 Rajeev Gupta Java Training
  • 54. Struts 2 and OGNL  The automation of data transfer and type conversion is one of the most powerful features of Struts 2. With the help of OGNL, the Struts 2 framework allows transfer of data onto more complex Java- side types like List, Map, etc.  OGNL is the interface between the Struts 2 framework string-based HTTP Input and Output and the Java-based internal processing. Rajeev Gupta Java Training
  • 55. Rajeev Gupta Java Training
  • 56. can get valueStack object inside your action as follows Rajeev Gupta Java Training
  • 57. Once you have a ValueStack object, you can use following methods to manipulate that object Rajeev Gupta Java Training
  • 58. Rajeev Gupta Java Training
  • 59. Rajeev Gupta Java Training
  • 60. # Control tags Rajeev Gupta Java Training
  • 61. Generic tags  Struts2 tags are divided into generic and UI tags  Generic tags  Used for controlling flow of data  And for data extraction from the value stack.  There are two type of generic tags  Control tags  Data tags  UI tags  Concern about form creation Rajeev Gupta Java Training
  • 62. Control tags if iterator A kind of for loop to iterate for collection array etc <s:if test="%{true}"> this line will be displayed. Ex: </s:if> <s:iterator status="stat“ value="{11,22,33,44,55,66}"> <s:property value="#stat.index"/> <s:if test="%{false}"> <s:property value="top"/> this line will be displayed. <s:if test="#stat.last==false">,</s:if> </s:iterator> </s:if> else <s:if test="type=="manager"> your are an manager </s:if> <s:else> not an manager </s:if> Rajeev Gupta Java Training
  • 63. Control tags append used to append collection objects to an single collection <s:append id="myAppender"> <s:param value="%{fruits}"/> <s:param value="%{books}"/> <s:param value="%{colors}"/> </s:append> Now: <s:iterator value="%{#myAppender}"> </s:iterator>  So many tags, explore yourself  merge  sort  subset  generator  elseIf Rajeev Gupta Java Training
  • 64. Control tags  Setting values in an action  How to display in an view: Rajeev Gupta Java Training
  • 65. #Data Tags Rajeev Gupta Java Training
  • 66. Data tags  Data tags primary used for creating and manipulating data  helps to access data from value stack or help to put data to value stack  Examples a Similer to <a href..../> Ex: <s:url id="url" action="addAction"></s:url> <s:a href="%{url}">adding</s:a> Rajeev Gupta Java Training
  • 67. Data tags action Used to call actions direcly from jsp Ex: consider following in struts.xml <action name="regForm" class="com.RegistrationAction"> <result name="success">reg.jsp</result> </action> Now: in an jsp.... <s:action name="regForm" executeResult="true"/> by default it is false Rajeev Gupta Java Training
  • 68. Data tags push used to push the value on value stack id : used for referencing element value: specify value to be pushed to value stack make accessing data simple...use if you have to use that data object extensively.... Example : Consider below example , how use of push make easy to access session scoped varaibles…. <s:set name="user" value="#session['user']"/> <s:push value="#user"/> <s:property value="userName'/> .... <s:property value="address"/> </s:push> Rajeev Gupta Java Training
  • 69. Data tags calling an action from href <p><a href="<s:url action='hello'/>">Hello World</a></p> mapping of that action <action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> url tag with param <s:url action="hello" var="helloLink"> <s:param name="userName">Bruce Phillips</s:param> </s:url> <p><a href="${helloLink}">Hello Bruce Phillips</a></p> Rajeev Gupta Java Training
  • 70. Data tags date <s:date name="new java.util.Date()" format="dd/mmm/yyyy"/> <s:date name="new java.util.Date()" format="%{getText('app.date.format')}"/> include <s:include value="header.jsp"/> Lots of tags: please explore  Bean set text url property debug 18n etc… Rajeev Gupta Java Training
  • 71. # UI tags Rajeev Gupta Java Training
  • 72. UI tags  form  Label  checkboxlist  Hidden  file  Doubleselect  token  Combobox  password  Submit  textarea  Datetimepicker  checkbox  Optgroup  select  textfield  radio  head  optiontransferselect  reset  updownselect Rajeev Gupta Java Training
  • 73. UI tags  Please refer examples shared… Rajeev Gupta Java Training
  • 74. # Interceptors Rajeev Gupta Java Training
  • 75. Interceptors  Can execute code before and after execution  Are thread-safe  Can be used for  Validation  Pre populating fields  Double-submit prevention  Session control  Authentication  Type conversion Rajeev Gupta Java Training
  • 76. Interceptors  Interceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework.  AOP ie Aspect oriented programming is not the replacement of OOP but it is support concept to oops  Interceptors are conceptually the same as servlet filters. You can achieve the following using interceptors: Providing preprocessing logic before the action is called. Providing postprocessing logic after the action is called. Catching exceptions so that alternate processing can be performed. Many of the features provided in the Struts2 framework are implemented using interceptors Rajeev Gupta Java Training
  • 77. Interceptors • Struts2 comes with default list of Interceptors already configured in the application in struts-default.xml file. We can create our own custom Interceptors and plugin into a Struts2 based web application. • Framework creates an object of ActionInvocation that encapsulates the action and all the interceptors configured for that action. • Each interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in reverse order to perform post processing work. • Interceptors can alter the workflow of action. It may prevent the execution of action. Rajeev Gupta Java Training
  • 78. Interceptors  Interceptor examples include:  exception handling,  file uploading,  lifecycle callbacks and  validation etc.  In fact, as Struts2 bases much of its functionality on interceptors, it is not unlikely to have 7 or 8 interceptors assigned per action. Rajeev Gupta Java Training
  • 79. Some Interceptors in Struts 2(I)  Alias  Allows parameters to have different name aliases across requests.  checkbox  Assists in managing check boxes by adding a parameter  value of false for check boxes that are not checked.  conversionError  Places error information from converting strings to parameter types into the action's field errors.  createSession  Automatically creates an HTTP session if one does not already exist Rajeev Gupta Java Training
  • 80. Some Interceptors in Struts 2 (II)  Debugging  Provides several different debugging screens to the developer.  execAndWait  Sends the user to an intermediary waiting page while the action executes in the background.  Exception  Maps exceptions that are thrown from an action to a result, allowing automatic exception handling via redirection.  fileUpload  Facilitates easy file uploading.  i18n  Keeps track of the selected locale during a user's session.  logger  Provides simple logging by outputting the name of the action being executed. Rajeev Gupta Java Training
  • 81. Some Interceptors in Struts 2 (III)  Params  Sets the request parameters on the action.  prepare  This is typically used to do pre-processing work, such as setup database connections.  Profile  Allows simple profiling information to be logged for actions.  Scope  Stores and retrieves the action's state in the session or application scope. Rajeev Gupta Java Training
  • 82. Some Interceptors in Struts 2 (IV)  ServletConfig  Provides the action with access to various servlet-based information.  timer  Provides simple profiling information in the form of how long the action takes to execute.  Token  Checks the action for a valid token to prevent duplicate form submission.  Validation  Provides validation support for actions Rajeev Gupta Java Training
  • 83. Interceptors  How to use Interceptors?  Interceptor need to be configure in struts.xml file as <interceptor-ref name="params"/> <interceptor-ref name="timer" /> Rajeev Gupta Java Training
  • 84. Rajeev Gupta Java Training
  • 85. Mapping interceptor to actions Rajeev Gupta Java Training
  • 86. Important to note… Rajeev Gupta Java Training
  • 87. Custom interceptor  Steps 1. Create a class that implements Interceptor. and Implement the intercept(ActionInvocation invocation) method. 2. Configure the interceptor in the struts.xml and Link it to action. Rajeev Gupta Java Training
  • 88. Step 1: Create a class that implements com.opensymphony.xwork 2.interceptor.Interceptor. Implement the intercept(ActionInvoca tion invocation) This is the method responsible for calling the next interceptor or the action Rajeev Gupta Java Training
  • 89. Rajeev Gupta Java Training
  • 90. Step 2: Configure the interceptor in the struts.xml and Link it to action. Rajeev Gupta Java Training
  • 91. Interceptor will execute… Rajeev Gupta Java Training
  • 92. # validation framework Rajeev Gupta Java Training
  • 93. Validation  2 ways to do validation 1. with the help of ActionSupport 2. XML way, more flexible Rajeev Gupta Java Training
  • 94. Validation with with the help of ActionSupport  Steps Create an form Add validate() method to action class… Rajeev Gupta Java Training
  • 95. Validation with with the help of ActionSupport  Don’t forget to map for “input” in strut.xml  When the user presses the submit button, Struts 2 will automatically execute the validate method and if any of the if statements listed inside the method are true, Struts 2 will call its addFieldError method. If any errors have been added then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return input as the result of calling the action.  So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the index.jsp file. Rajeev Gupta Java Training
  • 96. Struts - XML Based validation  More flexible and powerful.  Steps 1. Create registration form 2. Create Action class say EmployeeReg Rajeev Gupta Java Training
  • 97. Struts - XML Based validation 3. Now create EmployeeReg- validation.xml validation file in same package in which EmployeeReg is stored.  If the action EmployeeReg then name of validation file must be EmployeeReg-validation.xml  create validation xml file in '[action-class]'-validation.xml  If we want Client side validation  Just add validate="true“ to <s:form…> this option let java script produce at client side…… Rajeev Gupta Java Training
  • 98. Struts-XML based validation  Refer given code…  Rajeev Gupta Java Training
  • 99. # Struts 2 Type Conversion Rajeev Gupta Java Training
  • 100. Struts 2 Type Conversion  Struts2 provide automatically type conversion for basic data types such as ....  Integer, Float, Double, Decimal  Date and Datetime  Arrays and Collections  Enumerations  Boolean  BigDecimal  What if we have user define object?  In that cases Struts 2 Type Conversion is very handy..... Rajeev Gupta Java Training
  • 101. # Internationalization (i18n) support Rajeev Gupta Java Training
  • 102. Internationalization  For implement i18n in we need 1. resource bundles 2. interceptors and 3. tag libraries  Hello world example (Refer code Provided) Rajeev Gupta Java Training
  • 103. Internationalization  We need not to worry about writing pages in different languages. All we have to do is to create a resource bundle for each language that you want.  The resource bundles will contain titles, messages, and other text in the language of your user.  Resource bundles are the file that contains the key/value pairs for the default language of your application.  To develop your application in multiple languages, you would have to maintain multiple property files corresponding to those languages/locale and define all the content in terms of key/value pairs. Rajeev Gupta Java Training
  • 104. Internationalization  For example if you are going to develop your application for US English (Default), Spanish, and Franch the you would have to create three properties files.  global.properties  global.properties: By default English (United States) will be applied  global_fr.properties: This will be used for Franch locale.  global_es.properties: This will be used for Spanish locale. Rajeev Gupta Java Training
  • 105. Rajeev Gupta Java Training