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 DataBase Connection Pooling

Overview


  • The Struts Framework leverages a DataSource object to manage its database connections
  • This DataSource includes all of the necessary functionality to manage a pool of JDBC connections that can be
    used either in a Java application or in a Struts Web application.

Configure DataSource in Struts application.
  • To leverage the built−in functionality of the ActionServlet, you simply need to add a new entry to the
    struts−config.xml file.
  • The <data−sources> element, which acts as the parent to all <data−source> elements, must
    be added prior to the <form−beans> and <action−mappings> elements.

<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=""/>
    </data-source>
  </data-sources>

</struts-config>
  • The <data−sources> element acts as a container for n−number of <data−source> subelements, which each
    represent individual DataSource instances.
Example:-


Creating a sample database







index.jsp
<%taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>

<html:form action="/go">
  <table>
    <tr>
      <td><bean:message key="id" />
      </td>
      <td><html:text property="id" /></td>
    </tr>
    <tr>
      <td><bean:message key="name" />
      </td>
      <td><html:text property="name" /></td>
    </tr>
    <html:errors />
    <tr>
      <td></td>
      <td><html:submit value="Add" /></td>
    </tr>
  </table>

</html:form>

MyForm.java
package mypack;

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 MyForm extends ActionForm {

  private String name;
  private int id;

  public int getId() {
    return id;
  }

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

  public String getName() {
    return this.name;
  }

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

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

    ActionErrors error = new ActionErrors();

    if (getId() <= 0)
      error.add("id"new ActionMessage("error.id"));
    else if (getName().equals(""))
      error.add("name"new ActionMessage("error.name"));

    return error;
  }
}


MyAction.java
package mypack;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.*;
import java.sql.*;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

public class MyAction extends org.apache.struts.action.Action {

  String target;

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

    MyForm form1 = (MyFormform;
    String s = form1.getName();
    int id1 = form1.getId();

    try {
      if (s.equals(""|| id1 <= 0) {
        target = "failure";
      else {
        target = "success";
        DataSource ds = getDataSource(request);
        Connection con = ds.getConnection();
        Statement st = con.createStatement();
        st.executeUpdate("insert into emp values('" + s + "','" + id1
            "')");
      }
    catch (Exception e) {
      response.getWriter().println(e);
    }
    return mapping.findForward(target);
    }
}


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=""/>
    </data-source>
  </data-sources>

    
    <form-beans>
        <form-bean name="myform" type="mypack.MyForm"/>
    </form-beans>
   
    <action-mappings>        
    <action path="/go"  name="myform" 
type=
"mypack.MyAction"
validate="true" input="/index.jsp">
       <forward name="success" path="/welcome.jsp"/>
       <forward name="failure" path="/index.jsp"/>
     </action>
    </action-mappings>   
    <message-resources parameter="message"/>
    
</struts-config>

welcome.jsp

<%taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
Id is
<bean:write name="myform" property="id" />
<br>
Name is
<bean:write name="myform" property="name"/>
<br>
This record is inserted

message.properties
name=<font size="4" color="blue">Enter Name</font>
id=<font size="4" color="blue">Enter Id</font>

error.name=<font size="4" color="red">Name cannot be blank</font>
error.id=<font size="4" color="red">Id cannot be blank</font>

Output:-
  • Whenn we run index.jsp and click on add button with giving Name.
  • Validation will be performed as shown below.

  • When we enter both emp_ud nad emp_name and click on add button
    it will added the  id and name into the database successfully
  • As shown below.






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)