vendredi 30 août 2013

How to create a module with 2 class (many2one) in OpenERP 7

It is very easy to create a module in OpenERP 7
  •  The following steps are required to create a new module "student" :
  1. Create a subdirectory in the .../OpenERP/Server/server/openerp/addons/  that name module "student_speciality".
  2.  Create a file Module description : __ openerp__.py
  3. Create the file containing Python objects : student_speciality.py
  4. Create .xml file that download data (views, menu items, data show ...) : student_speciality_view.xml
  5. Finaly create a file Module start : __init__.py
  • The __ openerp__.py file :
In the module directory created, you must add a __ openerp__.py file.
This file, which must be Python format is responsible for :
    1. Determine the XML files that will be analyzed during the initialization of the server, and also
    2. Determine the dependencies of the module created.
        This file must contain a Python dictionary with the following values​​:

        {
                "name" : "student_speciality",
                "version" : "0.1",
                "author" : "rsuna blog",
                "website" : "http://rsuna.blogspot.com/",
                "category" : "Unknown",
                "description": """ OpenERP Module with 2 class mano2one test rsuna blog """,
                "depends" : ['base'],
                "init_xml" : [ ],
                "demo_xml" : [ ],
                "update_xml" : ['student_speciality_view.xml'],
                "installable": True
        }

        • The student_speciality.py file :
        from osv import fields,osv

        class student(osv.osv):
            _name = 'student'
            _columns = {
                'name': fields.char('name',size=30,required=True, help='the name'),
                'first_name': fields.char('first name',size=30,required=True, help='the first name'),
                'birth_date': fields.date('birth date',size=30,required=True, help='the birth date'),
                'email': fields.char('email',size=50, help='the email'),
                'phone': fields.integer('phone',size=30, help='the phone'),
                'level': fields.many2one('specialty','Specialty', help='the Specialty'),
            }
        student()

        class specialty(osv.osv):
            _name = 'specialty'
            _columns = {
                'name': fields.char('Name specialty',size=50,required=True, help='the name specialty'),
                'level': fields.char('Level',size=50, help='the level'),
            }
        specialty()

        • The student_speciality_view.xml file :
        <?xml version="1.0"?>
        <openerp>
        <data>

            <record model="ir.ui.view" id="view_student_form">
                <field name="name">student.form</field>
                <field name="model">student</field>
                <field name="type">form</field>
                <field name="arch" type="xml">
                    <form string="student">
                        <field name="name" select="1"/>
                        <field name="first_name" select="2"/>
                        <field name="birth_date" select="0"/>
                        <field name="email" select="0"/>
                        <field name="phone" select="0"/>
                        <field name="level" select="0"/>

                    </form>
                </field>
            </record>
            <record model="ir.ui.view" id="view_student_tree">
                <field name="name">student.tree</field>
                <field name="model">student</field>
                <field name="type">tree</field>
                <field name="arch" type="xml">
                    <tree string="student">
                        <field name="name"/>
                        <field name="first_name"/>
                        <field name="birth_date"/>
                        <field name="email"/>
                        <field name="phone"/>
                        <field name="level"/>

                    </tree>
                </field>
            </record>
            <record model="ir.actions.act_window" id="action_student">
                <field name="name">Student</field>
                <field name="res_model">student</field>
                <field name="view_type">form</field>
                <field name="view_mode">tree,form</field>
            </record>
            <menuitem name="Student/Student" id="menu_student"/>
            <menuitem name="Student" id="menu_student_item" parent="menu_student" action="action_student"/>

            <record model="ir.ui.view" id="view_specialty_form">
                <field name="name">specialty.form</field>
                <field name="model">specialty</field>
                <field name="type">form</field>
                <field name="arch" type="xml">
                    <form string="specialty">
                        <field name="name" select="1"/>
                        <field name="level" select="2"/>

                    </form>
                </field>
            </record>
            <record model="ir.ui.view" id="view_specialty_tree">
                <field name="name">specialty.tree</field>
                <field name="model">specialty</field>
                <field name="type">tree</field>
                <field name="arch" type="xml">
                    <tree string="specialty">
                        <field name="name"/>
                        <field name="level"/>

                    </tree>
                </field>
            </record>
            <record model="ir.actions.act_window" id="action_specialty">
                <field name="name">Specialty</field>
                <field name="res_model">specialty</field>
                <field name="view_type">form</field>
                <field name="view_mode">tree,form</field>
            </record>
            <menuitem name="Specialty/Specialty" id="menu_specialty" action="action_specialty"/>
            <menuitem name="Specialty" id="menu_specialty_item" parent="menu_specialty" action="action_specialty"/>

        </data>
        </openerp>
        • The __init__.py file :
        The __init__.py  file is like any Python module, executed at the beginning of the program. It needs to import the Python files to be loaded.

        So if you create a "student.py" file containing the description of your items, you must write a line in  __init__.py :

        import student_speciality

        - After restarts service openrerp.
        go to Configuration -> Module installs, and makes a search in the area of ​​search aver the module name "student_speciality"



        - Click on install
        Congratulation, module installed !!




        jeudi 29 août 2013

        How to create a basic module in OpenERP 7

        It is very easy to create a module in OpenERP 7
        •  The following steps are required to create a new module "student" :
        1. Create a subdirectory in the .../OpenERP/Server/server/openerp/addons/  that name module "student".
        2.  Create a file Module description : __ openerp__.py
        3. Create the file containing Python objects : student.py
        4. Create .xml file that download data (views, menu items, data show ...) : student_view.xml
        5. Finaly create a file Module start : __init__.py
        • The __ openerp__.py file :
        In the module directory created, you must add a __ openerp__.py file.
        This file, which must be Python format is responsible for :
          1. Determine the XML files that will be analyzed during the initialization of the server, and also
          2. Determine the dependencies of the module created.
              This file must contain a Python dictionary with the following values​​:

              {
                      "name" : "student",
                      "version" : "0.1",
                      "author" : "rsuna blog",
                      "website" : "http://rsuna.blogspot.com/",
                      "category" : "Unknown",
                      "description": """ OpenERP Module test rsuna blog """,
                      "depends" : ['base'],
                      "init_xml" : [ ],
                      "demo_xml" : [ ],
                      "update_xml" : ['student_view.xml'],
                      "installable": True
              }

              • The student.py file :
              from osv import fields,osv
              class student(osv.osv):
                  _name = 'student'
                  _columns = {
                      'name': fields.char('Name',size=30,required=True, help='the name'),
                      'first_name': fields.char('First Name',size=30,required=True, help='the first name'),
                      'birth_date': fields.date('Birth Date',size=30,required=True, help='the birth date'),
                      'email': fields.char('Email',size=50, help='the email'),
                      'phone': fields.integer('Phone',size=30, help='the phone'),
                  }
              student()

              • The student_view.xml file :
              <?xml version="1.0"?>
              <openerp>
              <data>
                  <record model="ir.ui.view" id="view_student_form">
                      <field name="name">student.form</field>
                      <field name="model">student</field>
                      <field name="type">form</field>
                      <field name="arch" type="xml">
                          <form string="student">
                              <field name="name" select="1"/>
                              <field name="first_name" select="2"/>
                              <field name="birth_date" select="0"/>
                              <field name="email" select="0"/>
                              <field name="phone" select="0"/>
                          </form>
                      </field>
                  </record>
                  <record model="ir.ui.view" id="view_student_tree">
                      <field name="name">student.tree</field>
                      <field name="model">student</field>
                      <field name="type">tree</field>
                      <field name="arch" type="xml">
                          <tree string="student">
                              <field name="name"/>
                              <field name="first_name"/>
                              <field name="birth_date"/>
                              <field name="email"/>
                              <field name="phone"/>
                          </tree>
                      </field>
                  </record>
                  <record model="ir.actions.act_window" id="action_student">
                      <field name="name">Student</field>
                      <field name="res_model">student</field>
                      <field name="view_type">form</field>
                      <field name="view_mode">tree,form</field>
                  </record>
                      <menuitem name="Student/Student" id="menu_student" action="action_student"/>
              <menuitem name="Student" id="menu_student_student_item" parent="menu_student" action="action_student"/>
              </data>
              </openerp>

              • The __init__.py file :
              The __init__.py  file is like any Python module, executed at the beginning of the program. It needs to import the Python files to be loaded.

              So if you create a "student.py" file containing the description of your items, you must write a line in  __init__.py :

              - After restarts service openrerp.
              go to Configuration -> Module installs, and makes a search in the area of ​​search aver the module name "student"

              - Click on install
              Congratulation, module installed !!




              vendredi 23 août 2013

              OpenERP development environment in Windows using Eclipse




              Versions Used:
                      OpenERP        -      6.0.3
                      Postgresql       -      9.0.4
                      Eclipse            -       3.7 (Indigo) 

              1) Download eclipse sdk(Indigo,latest version) and unzip it
                             http://www.eclipse.org/downloads/download.php?file=/eclipse/downloads/drops/R-3.7-201106131736/eclipse-SDK-3.7-win32.zip

              2) To run eclipse a java based application requires java jre to be installed.Download and install from
                               http://www.oracle.com/technetwork/java/javase/downloads/index-jdk5-jsp-142662.html
               
                      After installation, we need to add the jre bin path into system environment variable PATH.In my case jre bin
                       was at 'C:\Program Files\Java\jre1.5.0_22\bin'.similarily add the jre bin path of your installation.
                        (My computers-->properties-->Advanced System Setting-->Environment Variable-->PATH)

              3)Download the zip file from here which contains python interpretor and other python packages needed by OpenERP.
                     Extract and run the batch file 1 which installs python and  its associated libraries.we need to add following path
                     to system environment variable PATH before running the batch file 2 since it requires python as windows
                     command to run python scripts to install some more python packages.
              (;C:\Python25;C:\Python25\Scripts;C:\Python25\bin;C:\Python25\libs;C:\Python25\Lib\site-packages;C:\Python25\include;C:\Python25\DLLs)
                     
                       Zip files conatins packages downloaded from the following links
                              a)http://bazaar.launchpad.net/~openerp/openerp/win-installer-trunk/files/head%3A/dependencies/
               
                             b)http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.5.exe
               
                             c)http://ftp.edgewall.com/pub/babel/Babel-0.9.4.tar.gz
               
                             d)http://download.cherrypy.org/cherrypy/3.1.2/CherryPy-3.1.2.tar.gz
               
                             e)http://pypi.python.org/packages/source/s/simplejson/simplejson-2.0.9.tar.gz
               
                             f)http://pypi.python.org/packages/source/F/FormEncode/FormEncode-1.2.2.tar.gz
                  
              4)Install PyDev plugin in eclipse
                            a)help -> Install New Software.
                            b)In Install dialog box, Click Add.
                            c)Give name ‘pydev’ and type the path. i.e. http://pydev.org/updates.
                            d)click ok.
                            e)select pydev checkbox and follow the steps by clicking finish
                   
              5)Adding python in eclipse can be done by
                           a)window -> Preferences
                           b)In Preferences dialog box expand pydev from left side tree
                           c)click on Interpreter-Python
                           d)click new on right side of python Interpreters
                           e)locate the python.exe in the installed path e.g. C:\Python25\python.exe via Browse button and also
                              give the name to this interpreter(Python25)
                           f)click ok then again ok
                    
              6)Download and unzip tarballs for OpenERP 6.0.3 server, Client and Web-client using the following paths.
                       Unzip all these packages to separate folders on same path like Client, Server, Webclient folders in
                       C:\OpenERP path.
                                a)http://www.openerp.com/download/stable/source/openerp-server-6.0.3.tar.gz
               
                               b)http://www.openerp.com/download/stable/source/openerp-client-6.0.3.tar.gz
               
                               c)http://www.openerp.com/download/stable/source/openerp-web-6.0.3.tar.gz
                    
              7)Now we need to create PyDev projects in Eclipse for each of three projects i.e. Server, Client, and Webclient.
                        we can name the PyDev project as for eg:OpenERPClient, OpenERPServer and OpenERPWebClient and
                        for each we have to uncheck the option Use Default and browse for the path where we have unzipped each of
                        packages(C:\OpenERP).we have to choose project type as Python and its grammar version as 2.5 and
                        Interpreter as Python 2.5.
                     
              8)Download  and Install postgresql.
                           a)http://www.enterprisedb.com/products-services-training/pgdownload#windows
                           b)It will prompt for password and port number during installation process .If already postgresql older version
                              is runnning on your machine then enter port 5433 else enter 5432.
                           c)Create a new postgres user , start-->all programs-->postgresql 9.0-->pgadmin3
                           d)servers-->postgresql 9.0 right click on connect and enter password when prompted
                           e)mouse over login role right click new login role and enter role name(eg. 'openpg') and password
                              (eg. 'openpgpwd') and in the second tab role privileges above check all boxes(Superuser,Can Create....)
                      
              9)Now need to create configuration file for openerp-server with following options and copy conf file  to the bin
                        folder located in the path where we’ve unzipped server’s source code e.g. C:\OpenERP\server\bin
              1. [options]
              2. without_demo = False
              3. smtp_port = 25
              4. db_password = openpgpwd           (password you had given for the new role created in postgresql)
              5. xmlrpcs_interface = 
              6. syslog = False
              7. logrotate = True
              8. xmlrpcs_port = 8071               (change port here if already allinone setup has been installed,say 8061)
              9. test_report_directory = False
              10. list_db = True
              11. timezone = False
              12. xmlrpc_interface = 
              13. test_file = False
              14. cache_timeout = 100000
              15. smtp_password = False
              16. secure_pkey_file = server.pkey
              17. xmlrpc_port = 8069                (change port here if already allinone setup has been installed,say 8059)
              18. log_level = info
              19. xmlrpc = True
              20. test_disable = False
              21. admin_passwd = admin
              22. assert_exit_level = error
              23. smtp_server = localhost
              24. static_http_url_prefix = None
              25. test_commit = False
              26. xmlrpcs = True
              27. demo = {}
              28. login_message = False
              29. import_partial = 
              30. pidfile = None
              31. db_maxconn = 64
              32. stop_after_init = True
              33. osv_memory_count_limit = False
              34. reportgz = False
              35. osv_memory_age_limit = 1.0
              36. netrpc_port = 8070                 (change port here if already allinone setup has been installed,say 8060)
              37. db_port =5432                      (change port value as given by you at the time of postgresql-9.0 installation)
              38. db_name = False
              39. debug_mode = False
              40. netrpc = True
              41. secure_cert_file = server.cert
              42. csv_internal_sep = ,
              43. pg_path = None
              44. static_http_enable = False
              45. translate_modules = ['all']
              46. smtp_ssl = False
              47. root_path = C:\OpenERP\server      (change root_path to where you have extracted OpenERP Server)
              48. netrpc_interface = 
              49. smtp_user = False
              50. db_user = openpg                   (new login role you have created in postgresql)
              51. db_host =localhost
              52. email_from = False
              53. addons_path = C:\OpenERP\server\bin\addons  (change addons_path to addons directory present in root_path )      
              54. static_http_document_root = None
                    
              10)In Eclipse package explorer, open the list of Server -> open Bin -> Right Click on openerp-server.py 
                      Mouse Over ‘Run As’ -> Select ‘Python Run. In the same manner you can run openerp-client and openerp-web.
                  Note :
                     
                      a)IF no other installation of OpenERP are there you can use the default values for netrpc,xmlrpc and xmlrpcs
                      b)IF you have changed the netrpc port value then you should also change value of 'openerp.server.port' to
                         corresponding netrpc port value in  web/doc/openerp-web.cfg.
                       c)Similarily when trying to connect server with openerp-client also need to change netrpc-port to same.

              OpenERP development environment in Ubuntu using Eclipse



              Version Used:
              OpenERP    :     6.1
              Postgresql   :     9.1
              Eclispe        :     latest in ubuntu repository
              Run the following commands from the terminal.

              1) Installs eclipse and its dependencies.
                                sudo apt-get update
                                sudo apt-get install  eclipse

              2) Installs python and its libraries packages required for openerp-server
                              sudo apt-get install python python-psycopg2 python-reportlab python-pychart python-pydot 
                               python-egenix-mxdatetime python-lxml python-libxslt1 python-tz python-dateutil python-vobject
                               python-mako python-yaml python-dev python-setuptools python-pybabel

              3) OpenerpERP server uses postgresql database server for its working so,
                               sudo apt-get install python-software-properties
                               sudo add-apt-repository ppa:pitti/postgresql
                               sudo apt-get update
                               sudo apt-get install postgresql-9.1 postgresql-client-9.1 postgresql-contrib-9.1


              4) Create a database user for OpenERP in postgresql server, who can create  databases and manipulate them.
                               sudo su postgres
                               createuser <system-user-name> (enter "y" when prompted for super user role)
                               exit
                
              5) Openerp-server 6.1 requires Werkzeug and Python-openid packages to be installed.
                                 wget http://pypi.python.org/packages/source/W/Werkzeug/
                                      Werkzeug-0.8.3.tar.gz#md5=12aa03e302ce49da98703938f257347a  (copy the full link)

                                 tar -zxvf  Werkzeug-0.8.3.tar.gz
                                 cd Werkzeug-0.8.3
                                 python setup.py install
                                 cd ..
                                 wget http://pypi.python.org/packages/source/p/python-openid/
                                      python-openid-2.2.5.tar.gz#md5=393f48b162ec29c3de9e2973548ea50d  (copy the full link)

                                 tar -zxvf python-openid/python-openid-2.2.5.tar.gz
                                 cd python-openid-2.2.5
                                 python setup.py install
                                 cd ..
                
              6) Install PyDev plugin in eclipse
                          a)help -> Install New Software.
                          b)In Install dialog box, Click Add.
                          c)Give name ‘pydev’ and type the path. i.e.
                          d)click ok.
                          e)select pydev checkbox and follow the steps by clicking finish
                 
              7) Adding python in eclipse can be done by
                         a)window -> Preferences
                         b)In Preferences dialog box expand pydev from left side tree
                         c)click on Interpreter-Python
                         d)click new (python interpreter)
                         e)browse and select  "File System-->usr-->bin-->python" and  also give name "python2.6"
                         f) click ok then again ok
                 
              8) Download Openerp 6.1 source tarball from,
                          http://nightly.openerp.com/6.1/releases/openerp-6.1-1.tar.gz
                 
              9) Extract the tarball downloaded and create a folder Openerp and move the tarball and extract it there, rename it to Openerp-6.1
                
              10) Switch the workspace folder to created Openerp folder and create a new Pydev project in eclipse named Openerp-6.1.
                        New-> project --> Pydev --> Pydev project
                        project name - Openerp-6.1
                        check Use default
                        Press F5 after creating the project to refresh the workspace.
                 
              11) In Eclipse package explorer, Rename openerp-server in Openerp-6.1 folder to openerp-server.py.
                        Right Click on,  openerp-server.py --> Run as --> Python run.
                          Openerp web can be accessed from the browser through browser http://localhost:8069.


              src -> zbeanztech.com

              lundi 19 août 2013

              JSF 2 Internationalization

              n JSF application, you can change your application locale programmatically like this :
              //this example change locale to france
              FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale('fr');
              It makes JSF support for internationalization or multiple languages easily.

              Complete JSF internationalization example

              In this tutorial, we show you a JSF 2.0 web application, which display a welcome page, retrieve a welcome message from properties file, and change the welcome message dynamically based on the selected language.

              1. Project Folder

              Directory structure for this example.
              jsf2-internationalization-folder

              2. Properties file

              Here’s two properties files to store English and Chinese message.
              welcome.properties
              welcome.jsf = Happy learning JSF 2.0
              welcome_zh_CN.properties
              welcome.jsf = \u5feb\u4e50\u5b66\u4e60 JSF 2.0
              Note
              For UTF-8 or non-English characters, for example Chinese , you should encode it with native2ascii tool.

              3. faces-config.xml

              Include above properties file into your JSF application, and declared “en” as your default application locale.
              faces-config.xml
              <?xml version="1.0" encoding="UTF-8"?>
              <faces-config
                  xmlns="http://java.sun.com/xml/ns/javaee"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                  http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
                  version="2.0">
                   <application>
                       <locale-config>
                            <default-locale>en</default-locale>
                       </locale-config>
                  <resource-bundle>
                <base-name>com.rsuna.welcome</base-name>
                <var>msg</var>
                  </resource-bundle>
                   </application>
              </faces-config>

              4. Managed Bean

              A managed bean, which provide language selection list , and a value change event listener to change the locale programmatically.
              LanguageBean .java
              package com.rsuna;
               
              import java.io.Serializable;
              import java.util.LinkedHashMap;
              import java.util.Locale;
              import java.util.Map;
               
              import javax.faces.bean.ManagedBean;
              import javax.faces.bean.SessionScoped;
              import javax.faces.context.FacesContext;
              import javax.faces.event.ValueChangeEvent;
               
              @ManagedBean(name="language")
              @SessionScoped
              public class LanguageBean implements Serializable{
               
               private static final long serialVersionUID = 1L;
               
               private String localeCode;
               
               private static Map<String,Object> countries;
               static{
                countries = new LinkedHashMap<String,Object>();
                countries.put("English", Locale.ENGLISH); //label, value
                countries.put("Chinese", Locale.SIMPLIFIED_CHINESE);
               }
               
               public Map<String, Object> getCountriesInMap() {
                return countries;
               }
               
               
               public String getLocaleCode() {
                return localeCode;
               }
               
               
               public void setLocaleCode(String localeCode) {
                this.localeCode = localeCode;
               }
               
               //value change event listener
               public void countryLocaleCodeChanged(ValueChangeEvent e){
               
                String newLocaleValue = e.getNewValue().toString();
               
                //loop country map to compare the locale code
                              for (Map.Entry<String, Object> entry : countries.entrySet()) {
               
                          if(entry.getValue().toString().equals(newLocaleValue)){
               
                        FacesContext.getCurrentInstance()
                         .getViewRoot().setLocale((Locale)entry.getValue());
               
                         }
                             }
               }
               
              }

              5. JSF Page

              A JSF page to display a welcome message from properties file, and attach a value change event listener to a dropdown box.
              <?xml version="1.0" encoding="UTF-8"?>
              <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
              <html xmlns="http://www.w3.org/1999/xhtml"   
                    xmlns:h="http://java.sun.com/jsf/html"
                    xmlns:f="http://java.sun.com/jsf/core"
                    xmlns:ui="http://java.sun.com/jsf/facelets"
                    >
               
                  <h:body>
               
                   <h1>JSF 2 internationalization example</h1>
               
                   <h:form>
               
               <h3>
                <h:outputText value="#{msg['welcome.jsf']}" />
               </h3>
               
               <h:panelGrid columns="2">
               
                Language : 
                <h:selectOneMenu value="#{language.localeCode}" onchange="submit()"
                 valueChangeListener="#{language.countryLocaleCodeChanged}">
                    <f:selectItems value="#{language.countriesInMap}" /> 
                   </h:selectOneMenu>
               
               </h:panelGrid>
               
                    </h:form>
               
                  </h:body>
              </html>

              6. Demo

              URL : http://localhost:8080/JavaServerFaces/faces/default.xhtml
              Default, locale English is display.
              jsf2-internationalization-example-1
              If user changes the dropdown box language, it will fire a value change event listener and change the application locale accordingly.
              jsf2-internationalization-example-2

              src->mkyong.com

              samedi 10 août 2013

              Dynamic Method Invocation

              This is a continuation of the previous example ( DispatchAction functionality in Struts 2 ). In this example you will see how you can avoid configuring a seperate action mapping for each method in the Action class by using the wildcard method. Look at the following action mapping.
              <!DOCTYPE struts PUBLIC
              "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
              "http://struts.apache.org/dtds/struts-2.0.dtd">
              
              <struts>
                  <package name="default" extends="struts-default">
                      <action name="*User" method="{1}" class="rsuna.UserAction">
                          <result name="success">/success.jsp</result>
                      </action>
                  </package>
              </struts>
              
              
              Note the similarity between the action mapping and the following request URLs in this page.
              <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
                  pageEncoding="ISO-8859-1"%>
              <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
              <%@taglib uri="/struts-tags" prefix="s" %>
              <html>
              <head>
              <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
              <title>Insert title here</title>
              </head>
              <body>
                  <s:form action="User" >
                      <s:submit />
                      <s:submit action="addUser" value="Add" />
                      <s:submit action="updateUser" value="Update" />
                      <s:submit action="deleteUser" value="Delete" />
                  </s:form>
              </body>
              </html>
              
              
              As you can see we have replaced all the method names with an asterisk symbol. 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.
              vaannila.com

              DispatchAction in Struts 2

              In Struts 1 DispatchAction helps us to group a set of related functions into a single action. Struts 2 in all actions by default provide this functionality. To use this feature, we need to create multiple methods with the same signature of the execute () method, only the method name change.

              In our example, the useraction class contains all functions related to a user as addUser () UpdateUser () and deleteUser ().

              package rsuna;
              
              import com.opensymphony.xwork2.ActionSupport;
              
              public class UserAction extends ActionSupport{
              
               private String message;
              
               public String execute()
               {
                message = "Inside execute method";
                return SUCCESS;
               }
              
               public String add()
               {
                message = "Inside add method";
                return SUCCESS;
               }
              
               public String update()
               {
                message = "Inside update method";
                return SUCCESS;
               }
              
               public String delete()
               {
                message = "Inside delete method";
                return SUCCESS;
               }
              
               public String getMessage() {
                return message;
               }
              
               public void setMessage(String message) {
                this.message = message;
               }
              
              }
              
              
              
              
              Unlike Struts 1 you can even have the execute() method along with the other methods in the Action class. We need to specify which method in the action class will be called while configuring the action mapping. A separate action mapping needs to be created for each method in the action class. The following action mapping is done in the struts.xml file.
              <!DOCTYPE struts PUBLIC
              "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
              "http://struts.apache.org/dtds/struts-2.0.dtd">
              
              <struts>
                  <package name="default" extends="struts-default">
                      <action name="User" class="rsuna.UserAction">
                          <result name="success">/success.jsp</result>
                      </action>
                      <action name="addUser" method="add" class="rsuna.UserAction">
                          <result name="success">/success.jsp</result>
                      </action>
                      <action name="updateUser" method="update" class="rsuna.UserAction">
                          <result name="success">/success.jsp</result>
                      </action>
                      <action name="deleteUser" method="delete" class="rsuna.UserAction">
                          <result name="success">/success.jsp</result>
                      </action>
                  </package>
              </struts>
              Note that we use the same action class in all the action mappings. When the request URL is "User" the execute() method in the UserAction class will be invoked. When the request URL is "addUser" the add() method in the UserAction class will be invoked, this is specified using the method attribute of the action tag. Similarly for update and delete request the updateUser() and deleteUser() methods will be invoked respectively.
              Configuring a seperate action mapping for each method in the action class can be avoided by using an another feature of Struts 2 called Dynamic Method Invocation. The next example explains how to do this. ( Dynamic Method Invocation)
              In the index.jsp page we create four different buttons to invoke the different methods in the UserActionclass. The submit tag is used to create the buttons in the jsp page.
              <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
              pageEncoding="ISO-8859-1"%>
              <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
              <%@taglib uri="/struts-tags" prefix="s" %>
              <html>
              <head>
              <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
              <title>Insert title here</title>
              </head>
              <body>
              <s:form action="User" >
                  <s:submit />
                  <s:submit action="addUser" value="Add" />
                  <s:submit action="updateUser" value="Update" />
                  <s:submit action="deleteUser" value="Delete" />
              </s:form>
              </body>
              </html>
              Now lets execute the example. On running the example the following page will be displayed to the user. When the user click a button the appropriate method in the UserAction class gets invoked.
              When the user clicks the Add button the addUser() method in the UserAction class gets executed and the following page is displayed to the user.
              vaannila.com

              Share

              Twitter Delicious Facebook Digg Stumbleupon Favorites More