aspose file tools*
The moose likes Struts and the fly likes Could not get the connection in struts database application Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "Could not get the connection in struts database application" Watch "Could not get the connection in struts database application" New topic
Author

Could not get the connection in struts database application

Ramesh kangamuthu
Ranch Hand

Joined: Mar 13, 2007
Posts: 79
Hi,

I worked in a struts database application, which access the oracle database using commons datasource and I configured it in the struts-config.xml and set it in the resource reference to access from JNDI.I followed the java case sensistiveness and no typos.I specified the type of the datasource as org.apache.commons.dbcp.BasicDataSource with key "jdbc/testess", that was configured as JNDI name using resource reference utility in the Netbeans IDE. In the resource reference, I specified the type as javax.sql.DataSource. Should it be differ from the type attribute of the datasource element specified in the struts-config.xml ? But in the resource reference, there is no option for the type org.apache.commons.dbcp.BasicDataSource but only four option among them I chose javax.sql.DataSource. I have given the code here. Please provide your valuable help to solve the problem.

with best regards,
Ramesh K

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 key="jdbc/testess" type="org.apache.commons.dbcp.BasicDataSource">
<set-property
property="driverClass"
value="oracle.jdbc.OracleDriver" />
<set-property
property="url"
value="jdbc racle:thin:@windev:1521:testess"/>
<set-property
property="username"
value="testess" />
<set-property
property="password"
value="testess" />
<set-property
property="maxActive"
value="10" />
<set-property
property="maxWait"
value="5000" />
<set-property
property="defaultAutoCommit"
value="false" />
<set-property
property="defaultReadOnly"
value="false" />
<set-property
property="validationQuery"
value="SELECT COUNT(*) FROM Users" />
</data-source>
</data-sources>

<form-beans>
<form-bean name="ChangePasswordActionForm" type="user.form.ChangePasswordActionForm"/>
<form-bean name="LoginForm" type="user.form.LoginForm"/>
<form-bean name="UserRegistrationForm" type="user.form.UserRegistrationForm"/>
</form-beans>

<global-exceptions>

</global-exceptions>

<global-forwards>

</global-forwards>

<action-mappings>
<action input="/Login.jsp" name="LoginForm" path="/login" scope="session" type="user.action.LoginAction">
<forward name="success" path="/Welcome.jsp"/>
<forward name="failure" path="/Login.jsp"/>
</action>
<action input="/UserRegistration.jsp" name="UserRegistrationForm" path="/userRegistration" scope="session" type="user.action.UserRegistrationAction">
<forward name="success" path="/Login.jsp"/>
<forward name="failure" path="/UserRegistration.jsp"/>
</action>
</action-mappings>

<message-resources parameter="user/ApplicationResources"/>

<!-- ========================= Tiles plugin ===============================-->
<!--
This plugin initialize Tiles definition factory. This later can takes some
parameters explained here after. The plugin first read parameters from
web.xml, thenoverload them with parameters defined here. All parameters
are optional.
The plugin should be declared in each struts-config file.
- definitions-config: (optional)
Specify configuration file names. There can be several comma
separated file names (default: ?? )
- moduleAware: (optional - struts1.1)
Specify if the Tiles definition factory is module aware. If true
(default), there will be one factory for each Struts module.
If false, there will be one common factory for all module. In this
later case, it is still needed to declare one plugin per module.
The factory will be initialized with parameters found in the first
initialized plugin (generally the one associated with the default
module).
true : One factory per module. (default)
false : one single shared factory for all modules
- definitions-parser-validate: (optional)
Specify if xml parser should validate the Tiles configuration file.
true : validate. DTD should be specified in file header (default)
false : no validation

Paths found in Tiles definitions are relative to the main context.
-->
<!-- ========================= Validator plugin ================================= -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>

</struts-config>


UserRegistrationAction.java

/*
* UserRegistrationAction.java
*
* Created on December 24, 2007, 8:03 PM
*/

package user.action;

import javax.servlet.http.HttpServletRequest;
import java.sql.*;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import user.form.UserRegistrationForm;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.*;
import java.io.PrintWriter;
/**
*
* @author ramesh.k
* @version
*/

public class UserRegistrationAction extends Action {

/* forward name="success" path="" */
private final static String SUCCESS = "success";

/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/

String pass="pass";
String strUsername;
String strPassword;
String strFirstname;
String strMiddlename;
String strLastname;
String strStreet_address;
int intPost_box_no;
int intPostal_code;
String strEmail_address;
String strState;
String strCountry;
String strCity;
String strTelephone;
int intMobile;
DataSource datasource;
Connection userConnection;
Statement userStatement;
PreparedStatement userPreparedStatement;
ResultSet userResultSet;
ActionForward forward;

public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response) {
UserRegistrationForm RegistrationForm = (UserRegistrationForm) form;// TODO Auto-generated method stub
//Getting writer
try
{
PrintWriter writer=response.getWriter();
//writer.println("User request paramaters are retrieved");
strUsername=RegistrationForm.getUsername();
strPassword=RegistrationForm.getPassword();
strFirstname=RegistrationForm.getFirstname();
strMiddlename=RegistrationForm.getMiddlename();
strLastname=RegistrationForm.getLastname();
strStreet_address=RegistrationForm.getStreet_address();
intPost_box_no=RegistrationForm.getPost_box_no();
intPostal_code=RegistrationForm.getPostal_code();
strEmail_address=RegistrationForm.getEmail_address();
strCountry=RegistrationForm.getCountry();
strState=RegistrationForm.getState();
strCity=RegistrationForm.getCity();
strTelephone=RegistrationForm.getTelephone();
intMobile=RegistrationForm.getMobile();

//Getting JNDI context
InitialContext ctx=new InitialContext();
Context ctxt=(Context)ctx.lookup("java:/comp/env");
if(ctx==null)
{
throw new SQLException("No Context");
}
DataSource dataSource=(DataSource)ctxt.lookup("jdbc/testess");
if(dataSource==null)
{
throw new SQLException("Data Source not Found");
}
//writer.println("Got the DataSource");
//userConnection=dataSource.getConnection();
if(userConnection==null)
{
throw new SQLException("Could not get the connection");
}
System.out.println("After getting DataSource Checking whether the user exists already");
writer.println("After getting DataSource Checking whether the user exists already");
userPreparedStatement=userConnection.prepareStatement("select username from Users where username=?");
userPreparedStatement.setString(1, strUsername);
userResultSet=userPreparedStatement.executeQuery();
while(userResultSet.next()) {
writer.println("Inside result set");
if(!(userResultSet.getString("username").equals(strUsername)))
{
saveUser();
forward=mapping.findForward("success");
}
else
{
forward=mapping.findForward("failure");
}
}
} catch(Exception ex) {
//ex.printStackTrace();
}
return(forward);
}
public void saveUser() {
try
{
userPreparedStatement=userConnection.prepareStatement("insert into Users values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
userPreparedStatement.setString(1,strUsername);
userPreparedStatement.setString(2,strPassword);
userPreparedStatement.setString(3,strFirstname);
userPreparedStatement.setString(4,strMiddlename);
userPreparedStatement.setString(5,strLastname);
userPreparedStatement.setString(6,strStreet_address);
userPreparedStatement.setInt(7,intPost_box_no);
userPreparedStatement.setInt(8,intPostal_code);
userPreparedStatement.setString(9,strEmail_address);
userPreparedStatement.setString(10,strCountry);
userPreparedStatement.setString(11,strState);
userPreparedStatement.setString(12,strCity);
userPreparedStatement.setString(13,strTelephone);
userPreparedStatement.setInt(14,intMobile);
userPreparedStatement.executeUpdate();
userPreparedStatement.close();
System.out.println("saveUser completes");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}

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>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
</jsp-config>
<resource-ref>
<description>It is a user Database</description>
<res-ref-name>jdbc/testess</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</web-app>
 
jQuery in Action, 2nd edition
 
subject: Could not get the connection in struts database application