Set up the Database Pooling with Struts
Previous | Home | Next |
Apache provides commons-pooling and commons-dbcp to get Struts Datasources to work on struts application.
We need commons-pool-1.1.jar, commonsdbcp-1.1.jar and struts-legacy.jar jar file. Copy these jars into lib folder of your struts web application. We need one more jar file mysql-connector-java-3.1.11-bin.jar to connect Struts application to MySQL. Struts need following configuration setting into struts-config.xml to configure following database for our struts based projects. This line will very first line in struts-config.xml.struts-config.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config><data-sources> <data-source type="org.apache.tomcat.dbcp.dbcp.BasicDataSource"> <set-property property="driverClassName" value="com.mysql.jdbc.Driver" /> <set-property property="url" value="jdbc:mysql://localhost/mydatabase" /> <set-property property="username" value="root" /> <set-property property="password" value="root" /> </data-source> </data-sources></struts-config>
To get DataSource in subclass of Action class use following code.InfoData.javapackage com.r4r; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.sql.*; import java.sql.*; public class InfoData extends Action { public ActionForward execute(ActionMapping mapping,ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception{ DataSource ds; Connection con=null; try { ds = getDataSource(request); con= dataSource.getConnection(); Statement stmt=con.createStatement(); ResultSet rst=stmt.executeQuery("select * from info"); while(rst.next()){ rst.getString("username"); } rst.close(); stmt.close(); } catch (Exception ex) { System.out.println(ex); } finally { con.close(); } } return mapping.findForward("success"); } }
Previous | Home | Next |