JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Struts DispatchAction

Overview

  • DispatchAction provides a mechanism for grouping a set of related functions into a single
    action, thus eliminating the need to create seperate actions for each functions.
Example:
  • In this example we will see how to group a set of user related actions like insert user, update user and delete user into a single action called MyAction
  • The class MyAction extends org.apache.struts.actions.DispatchAction.
  •  This class does not provide an implementation of the execute() method as the normal Action class does.
  • The DispatchAction uses the execute method to manage delegating the request to the
    individual methods based on the incoming request parameter.
  •  For example if the incoming parameter is "method=insert", then the insert method will be invoked.
  •  These methods should have similar signature as the execute method..

index.jsp
  • The name of the method to be invoked and the value of the input component should
    be the same.
<%taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<h3>Struts Dispatch Action Example..!</h3>
<html:form action="/go.do">

Select Opearation
<html:select property="method">
<html:option value="delete"/>delete
<html:option value="update"/>update
<html:option value="insert"/>insert
</html:select>
<html:submit/>
</html:form>

MyForm.java
package myform;

import org.apache.struts.action.ActionForm;

public class MyForm extends ActionForm {
  private String method;

  public String getMethod() {
    return method;
  }

  public void setMethod(String method) {
    this.method = method;
  }

}

MyAction.java
package myaction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import myform.MyForm;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class MyAction extends DispatchAction {
  String target = "success";

  public ActionForward delete(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    MyForm form1 = (MyFormform;

    request.setAttribute("op", form1.getMethod());

    return (mapping.findForward(target));
  }

  public ActionForward update(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    // request.setAttribute("op", "update  operation");
    MyForm form1 = (MyFormform;

    request.setAttribute("op", form1.getMethod());
    return (mapping.findForward(target));
  }

  public ActionForward insert(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    // request.setAttribute("op", "insert operation");
    MyForm form1 = (MyFormform;

    request.setAttribute("op", form1.getMethod());
    return (mapping.findForward(target));
  }

}
  • If you notice the signature of the insert, update and delete methods are similar to the
    execute method except the name.
  •  The next step is to create an action mapping for this action handler
  • . The request parameter name is specified using the parameter attribute.
    Here the request parameter name is method.
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD
 Struts Configuration 1.1//EN"

          "http://jakarta.apache.org/strut
s/dtds/struts-config_1_1.dtd"
>

<struts-config>
    <form-beans>
    <form-bean name="myform"
      type="myform.MyForm"/>
    </form-beans>

    <action-mappings>

    <action path="/go"
      type="myaction.MyAction"
      name="myform"
      parameter="method"
      input="/index.jsp">
      <forward name="success" path="/welcome.jsp"/>
    </action>

    </action-mappings>
</struts-config>


Welcome.jsp
<html>
<body>
<h3>
U have selected <%=request.getAttribute("op"%>
</h3>
</body>
</html>


Ouput:-
  • On Running the index.jsp file.


  • When the user Select delete operation.

  • When the user Select update operation.


  • When the user Select insert operation.




Download Eclipse Code without lib

Download code with lib(WAR)


Example:- Dispatch Action With DBCP CRUD Application
  • Insert Operation
  • Update Operation
  • Delete Operation
dataAdd.jsp

<%taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html:form action="/data">
Id  <html:text property="id" />

  <br>
  <br>
Name <html:text property="name" />
  <br>
  <br>

Select Opearation
<br>
  <br>
<html:radio property="method" value="delete" />Delete
<br>

  <html:radio property="method" value="update" />Update
<br>

  <html:radio property="method" value="insert" />Insert
<html:errors />
  <br>
  
  <html:submit />

</html:form>


dataForm.java

package data;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class dataForm extends ActionForm {
  private String name;
  private int id;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  private String method;

  public String getMethod() {
    return method;
  }

  public void setMethod(String method) {
    this.method = method;
  }

  @Override
  public ActionErrors validate(ActionMapping mapping,
      HttpServletRequest request) {

    ActionErrors err = new ActionErrors();
System.out.println("........."+method);
    if (method==null||method.equals(""))
      err.add("method"new ActionMessage("error.method"));

    else {
      if (getMethod().equals("delete")) {

        if (id <= 0)
          err.add("id"new ActionMessage("error.id"));
      }

      if (getMethod().equals("update")) {
        if (id <= 0)
          err.add("id"new ActionMessage("error.id"));

        else if (name.equals(""))
          err.add("name"new ActionMessage("error.name"));
      }

      if (getMethod().equals("insert")) {
        if (id <= 0)
          err.add("id"new ActionMessage("error.id"));

        else if (name.equals(""))
          err.add("name"new ActionMessage("error.name"));
      }
    }
    return err;
  }

}


dataAction.java

package data;

import java.sql.Connection;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class dataAction extends DispatchAction {

  String target;

  public ActionForward delete(ActionMapping mapping,
 ActionForm form,

      HttpServletRequest request,
HttpServletResponse response
)
      throws Exception {

    dataForm dform = (dataFormform;

    int id = Integer.parseInt(request.getParameter("id"));

    String method = dform.getMethod();

    if (id <= 0)
      target = "cancel";

    else if (method.equals(""))
      target = "cancel";
    
    else {
      DataSource ds = getDataSource(request);
      Connection con = ds.getConnection();
      Statement st = con.createStatement();
      st.executeUpdate("delete from  emp where
emp_id='" 
+ id + "'");
      target = "ok";
    }

    return mapping.findForward(target);
  }

  public ActionForward update(ActionMapping mapping,
 ActionForm form,

      HttpServletRequest request,
HttpServletResponse response
)
      throws Exception {
    dataForm dform = (dataFormform;
    int id = Integer.parseInt(request.getParameter("id"));
    String name = request.getParameter("name");

    String method = dform.getMethod();

    if (id <= 0)
      target = "cancel";

    else if (name == "")
      target = "cancel";

    else if (method.equals(""))
      target = "cancel";
    else {
      DataSource ds = getDataSource(request);
      Connection con = ds.getConnection();
      Statement st = con.createStatement();
      st.executeUpdate("update  emp set emp_name='"
 
+ name + "' where emp_id="
          + id + "");
      target = "ok";
    }

    return mapping.findForward(target);
  }

  public ActionForward insert(ActionMapping mapping,
 ActionForm form,

      HttpServletRequest request,
HttpServletResponse response
)
      throws Exception {
    dataForm dform = (dataFormform;
    int id = Integer.parseInt(request.getParameter("id"));
    String name = request.getParameter("name");

    String method = dform.getMethod();

    if (id <= 0)
      target = "cancel";

    else if (name == "")
      target = "cancel";

    else if (method.equals(""))
      target = "cancel";
    else {
      DataSource ds = getDataSource(request);
      Connection con = ds.getConnection();
      Statement st = con.createStatement();
      st.executeUpdate("insert into emp values("
 
+ id + ",'" + name
          "')");
      target = "ok";
    }

    return mapping.findForward(target);
  }

}

message.properties

error.name=<br><font size="3" color="red">
First name cannot be blank</font><br>

error.id=<br><font size="3" color="red">
Id cannot be blank</font><br>

error.method=<br><font size="3" color="red">
Please Select At Least One  Method </font><br>


struts-config.xml

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

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//
DTD Struts Configuration 1.2//EN"

          "http://jakarta.apache.org/struts
/dtds/struts-config_1_2.dtd"
>

<struts-config>

  <data-sources>
    <data-source type="org.apache.commons.dbcp.BasicDataSource">
      <set-property property="driverClassName"
value="com.mysql.jdbc.Driver" />
      <set-property property="url"
        value="jdbc:mysql://localhost:3306/test" />
      <set-property property="username"
 
value="root" />
      <set-property property="password"
 
value="developer" />
    </data-source>
  </data-sources>
  <form-beans>

    <form-bean name="dform" type="data.dataForm" />

  </form-beans>

  <action-mappings>

    <action type="data.dataAction" name="dform"
 
path="/data" scope="session"
      parameter="method" input="/dataAdd.jsp">

      <forward name="ok" path="/dataDisp.jsp" />
      <forward name="cancel" path="/dataAdd.jsp" />

    </action>

  </action-mappings>

  <message-resources parameter="message" />

</struts-config>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.
com/xml/ns/j2ee"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml
/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet
</servlet-
class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml
</param-value>

    </init-param>
  
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>
           dataAdd.jsp
        </welcome-file>
  </welcome-file-list>

</web-app>


Output:-
  • When we run  dataAdd.jsp and Enter both the id and name.
  • If we select  insert operation it will take both the id nad name insert the same into
    the emp table in the database.
  • As shown below.






  • Here Again if  we select Update operation
    it will  replace the name with Shankar as before javed of id =101.
  • As shown below.





  • If we select Delete, then it will delete the record of id=101 from the emp table in database
  • As shown below.






Download Eclipse Code without lib

Download code with lib(WAR)