Servlet-jdbc problem
hello all,
I am writing a simple servlet which will extract data (empno and empname) from a html form and insert in to database.
everything seems to work fine except it inserts in to the table empno and empname as it is without values.
if u can think of some reason and specify it would be great.
thanx once again.
mahesh
anyway i have those 2 small programs as below :
enterinfo.java - for generating entry form
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EnterInfo extends HttpServlet
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html><body>");
out.println("<form name=\"insertdata\" method=\"post\" action=\"msgservlet\">");
out.println("Emp No<input type=text name=empno><br>");
out.println("Emp Name<input type=text name=empname><br>");
out.println("<input type=submit value=send>");
out.println("</form></body></html>");
msgservlet.java - for extracting data and inserting data in to the table
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class msgservlet extends HttpServlet
private Connection con;
private PrintWriter out;
private Statement stmt;
public void init(ServletConfig conf) throws ServletException
super.init(conf);
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(ClassNotFoundException cnfe)
System.err.println("Details:"+cnfe);
System.exit(0);
try
conrjc();
//con=DriverManager.getConnection("jdbc:odbc:njdbc");
catch(SQLException sqle){
System.err.println("Details"+sqle);
public void conrjc() throws SQLException
con=DriverManager.getConnection("jdbc:odbc:njdbc");
public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{
res.setContentType("text/html");
try{
out=res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Sample JDBC Servlet</title>");
out.println("</head>");
out.println("<body>");
stmt=con.createStatement();
int eno=Integer.parseInt(req.getParameter("empno"));
String enm=req.getParameter("empname");
//String ins="insert into MYEMPLOYEE values('req.getParameter("empno")','req.getParameter("empname")')";
stmt.executeUpdate("insert into MYEMPLOYEE values(eno,enm)");
out.println("<h1>OK</h1>");
// stmt.close();
con.commit();
catch(SQLException se){
out.println("An SQL Exception was Thrown"+ se);
catch(IOException se){
out.println("An IO Exception was Thrown");
out.println("</body>");
out.println("</html>");
out.close();
public void destroy(){
try{
con.close();
catch(SQLException sqle){}
try using the following statement instead on the previous one...
stmt.executeUpdate("insert into MYEMPLOYEE values('"+eno+"','"+enm+"')");
Usually strings are passed as 'string' to be inserted into the database. Make sure you know what data type you are inserting into the database (from database design). However, prepared statement should work as well.
Hope this helps
AAJ
Similar Messages
-
JDBC Problem with Netscape Enterprise Server 3.61
I have created a servlet->JDBC(Thin driver for Oracle 7.3) model to communicate the ORacle Database on an UNIX box by using Netscape Enterprise Server 3.61. I got the following problems and if anyone could help me. Many many thanks.
java.lang.IllegalAccessError: JdbcDriver at
WhitePageSearch.doGet(WhitePageSearch.java:75) * at
javax.servlet.http.HttpServlet.service(HttpServlet.java:252) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:330) at
sun.servlet.netscape.NSRunner.run(NSRunner.java:144) at
netscape.server.applet.ServerApplet.handleRequest(ServerApplet.java:69)
at netscape.server.applet.HttpApplet.handleRequest(HttpApplet.java:680)
By the way. This model works fine on the servletrunner on my NT machine and I guess there are some problem on the Nescape Server setting.You need to install the Netscape Proxy plug-in.
You can find the plug-in at the BEA download site along with the instructions.
Once downloaded it took about 5 minutes to update a config file and have everything running.
Good Luck...
Daniel Astillero <[email protected]> wrote:
How can I configure Netscape Enterprise Server 3.5.1 to use WebLogic 5.1? -
Servlet Compilation Problem !
Hi,
I am just starting to learn servlets and I got problem in compiling them. I got compilation error in
import javax.servlet.*;statement. Seems that the compiler cannot find the servlet package. I got J2EE 1.4 beta installed on my machine but there is no servlet.jar package. I am using J2SDK 1.4.1_02, J2EE 1.4 beta and Tomcat 4.1.24.
Can anyone help me with my servlet compilation problem?
Thanks in advance!
Joshservlet.jar is here :
<tomcatdir>\common\lib
add it to your compiler classpath -
Servlets/JDBC vs. servlets/EJB performance comparison/benchmark
I have a PHB who believes that EJB has no ___performance___ benefit
against straightforward servlets/JSP/JDBC. Personally, I believe that
using EJB is more scalable instead of using servlets/JDBC with
connection pooling.
However, I am at a lost on how to prove it. There is all the theory, but
I would appreciate it if anyone has benchmarks or comparison of
servlets/JSP/JDBC and servlets/JSP/EJB performance, assuming that they
were tasked to do the same thing ( e.g. performance the same SQL
statement, on the same set of tables, etc. ).
Or some guide on how to setup such a benchmark and prove it internally.
In other words, the PHB needs numbers, showing performance and
scalability. In particular, I would like this to be in WLS 6.0.
Any help appreciated.First off, whether you use servlets + JDBC or servlets + EJB, you'll
most likely spend much of your time in the database.
I would strongly suggest that you avoid the servlets + JDBC
architecture. If you want to do straight JDBC code, then it's
preferable to use a stateless session EJB between the presentation layer
and the persistence layer.
So, you should definitely consider an architecture where you have:
servlets/jsp --> stateless session ejb --> JDBC code
Your servlet / jsp layer handles presentation.
The stateless session EJB layer abstracts the persistence layer and
handles transaction demarcation.
Modularity is important here. There's no reason that your presentation
layer should be concerned with your persistence logic. Your application
might be re-used or later enhanced with an Entity EJB, or JCA Connector,
or a JMS queue providing the persistence layer.
Also, you will usually have web or graphic designers who are modifying
the web pages. Generally, they should not be exposed to transactions
and jdbc code.
We optimize the RMI calls so they are just local method calls. The
stateless session ejb instances are pooled. You won't see much if any
performance overhead.
-- Rob
jms wrote:
>
I have a PHB who believes that EJB has no ___performance___ benefit
against straightforward servlets/JSP/JDBC. Personally, I believe that
using EJB is more scalable instead of using servlets/JDBC with
connection pooling.
However, I am at a lost on how to prove it. There is all the theory, but
I would appreciate it if anyone has benchmarks or comparison of
servlets/JSP/JDBC and servlets/JSP/EJB performance, assuming that they
were tasked to do the same thing ( e.g. performance the same SQL
statement, on the same set of tables, etc. ).
Or some guide on how to setup such a benchmark and prove it internally.
In other words, the PHB needs numbers, showing performance and
scalability. In particular, I would like this to be in WLS 6.0.
Any help appreciated.--
Coming Soon: Building J2EE Applications & BEA WebLogic Server
by Michael Girdley, Rob Woollen, and Sandra Emerson
http://learnweblogic.com -
Remote JDBC Problem with Oracle BPM Studio
Hi all, i am facing the Remote JDBC Problem with Oracle BPM Studio.
When i configure a Remote JDBC Connection for SQL in BPM Studio, it prompt me an error.
The SQL Connection is configured as following :
External Resource:
Name : MyDS
Type : SQL Database
Supported Types : Remote JDBC
Details:
Database Type : BPM's Oracle Driver Version:10, 11
J2EE : WLS
Lookup Name : MyAppDS
Configuration for "WLS"
Name : WLS
Type : J2EE Application Server
Supported Types : GENERIC_J2EE
Details:
Initial Context Factory : weblogic.jndi.WLInitialContextFactory
URL : t3://localhost:7001
But, when i try to connect to the Database by using this configuration, I will get an Exception.
An exception occurred while getting a resource from a connector.
Detail:The connector [[ MyDS : SQL : REMOTE_JDBC ]] caused an exception when getting a resource.
Caused by: An exception occurred while getting a resource from a connector.
Detail:The connector [[ WLS : J2EE : J2EE ]] caused an exception when getting a resource.
Caused by: javax.naming.NoInitialContextException: Cannot instantiate class: weblogic.jndi.WLInitialContextFactory [[ Root exception is java.lang.ClassNotFoundException: weblogic.jndi.WLInitialContextFactory ]]
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:657)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:197)
at fuego.jndi.FaultTolerantContext.createContext(FaultTolerantContext.java:726)
at fuego.jndi.FaultTolerantContext.<init>(FaultTolerantContext.java:79)
at fuego.connector.impl.GenericJ2EEConnector.createInitialContext(GenericJ2EEConnector.java:177)
at fuego.connector.impl.GenericJ2EEConnector.createStandaloneContext(GenericJ2EEConnector.java:98)
at fuego.connector.impl.BaseJ2EEConnector.getResource(BaseJ2EEConnector.java:92)
at fuego.connector.impl.BaseJ2EEConnector.getResource(BaseJ2EEConnector.java:76)
at fuego.connector.J2EEHelper.getReadOnlyContext(J2EEHelper.java:86)
... 12 more
Edited by: user2262377 on Jun 22, 2009 4:01 PMI guess the weblogic.jar is not included in the studio.
So, i added weblogic.jar (Weblogic 10.3) and wlclient.jar (Weblogic 10.3)
It is working in my simple java code. But, still not working in BPM Studio.
The error logs:
An exception occurred while getting a resource from a connector.
Detail:The connector [OFT_APP_DS:SQL:REMOTE_JDBC] caused an exception when getting a resource.
Caused by: java.lang.Object cannot be cast to java.io.Serializable
fuego.connector.ConnectorException: An exception occurred while getting a resource from a connector.
Detail:The connector [OFT_APP_DS:SQL:REMOTE_JDBC] caused an exception when getting a resource.
at fuego.connector.ConnectorException.exceptionOnGetResource(ConnectorException.java:88)
at fuego.connector.JDBCHelper.getReadOnlyConnection(JDBCHelper.java:93)
at fuego.sqlintrospector.BrowserPanel.connect(BrowserPanel.java:395)
at fuego.sqlintrospector.BrowserPanel.populateTree(BrowserPanel.java:200)
at fuego.ui.wizards.ui.CheckTreeBrowser$1.construct(CheckTreeBrowser.java:63)
at fuego.ui.SwingWorker$2.run(SwingWorker.java:39)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.ClassCastException: java.lang.Object cannot be cast to java.io.Serializable
at weblogic.iiop.IIOPOutputStream.writeAny(IIOPOutputStream.java:1588)
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2231)
at weblogic.utils.io.ObjectStreamClass.writeFields(ObjectStreamClass.java:413)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:235)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:225)
at weblogic.corba.utils.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:182)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1963)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:2001)
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2266)
at weblogic.jdbc.common.internal.RmiDataSource_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:477)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:473)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173) -
Servlet chaining problem..
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Deblink extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String contentType = req.getContentType(); // get the incoming type
if (contentType == null) return; // nothing incoming, nothing to do
res.setContentType(contentType); // set outgoing type to be incoming type
PrintWriter out = res.getWriter();
BufferedReader in = req.getReader();
String line = null;
while ((line = in.readLine()) != null) {
line = replace(line, "<BLINK>", "");
line = replace(line, "</BLINK>", "");
out.println(line);
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
private String replace(String line, String oldString, String newString) {
int index = 0;
while ((index = line.indexOf(oldString, index)) >= 0) {
// Replace the old string with the new string (inefficiently)
line = line.substring(0, index) +
newString +
line.substring(index + oldString.length());
index += newString.length();
return line;
What is pre request fo above code to work.
I had tried this many time but it is not working, what will be calling servlet look likeAnd can you explain why your title is "Servlet chaining problem"?
-
Please let me know where I can find more information regarding iPlanet usage/deployment/configuring/tuning etc for support of technologies - like EJB, JSP/servlets, JDBC, connection pooling, XML, load balancing, JDBC & Transactions
(I have already read the 'Getting Started with the iPlanet Application Server' part five and six - http://developer.iplanet.com/appserver/testdrive/partfive.jsp and partsix.jsp)(I am using the ias testdrive version).Hi,
It's difficult to explain unless the J2EE architecture is understood. Also, explaining things like load balancing, Transactions, tuning, are bit vague and could blow the disk space of this site.
To get started, the best way is to test the sample applications and the best part is you don't require internet connection to follow each steps. Install iWS and iAS, open browser, type in http://hostname:port/ias-samples/index.html. You can find links to the sample applications bundled. Please follow the steps given on deploying the application. This will enable you to a higher level.
Regards
Ganesh .R
Developer Technical Support
Sun Microsystems
http://www.sun.com/developers/support -
JDBC/Servlets Connectivity Problems.
Hi,
I'm new to Java development.
I'm trying to run this simple Servlet on
OS : Sun Solaris 2.6
Web Server : Netscape Enterprise Server
Database : Oracle 8i
JDK2 and JSDK2 installed on the Server.
JDBC Driver : Native Oracle JDBC Driver
This program works perfect on the Server if I run it as a program (Not a Servlet). However when running it as a Servlet, JUST DOESN't do ANYTHING. Doesn't return any error nor does execute the SQL Command.
Also how can I enable tracing to Trap errors generated on the Server by the Servlet.
Thanks for all your help....
Here's the Pogram:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import oracle.jdbc.driver.*;
public class CreateTable1 extends HttpServlet {
public void init(ServletConfig config)
throws ServletException {
super.init(config);
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
out.println("<html>");
out.println("<head><title>CR2Reat Table Server</title></head>");
out.println("<body>");
out.println("<br>Before Create...");
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection("jdbc:oracle:kprb:@oracle","uername","password");
Statement statement = con.createStatement();
statement.executeUpdate("CREATE TABLE kj_newCont1" +
"(title_id NUMBER, title_name VARCHAR2(50)," +
"rating CHAR(5), price NUMBER(7,2), quantity NUMBER," +
"type_id INTEGER, category_id INTEGER)");
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
catch (Exception e) {
System.err.println(e.getMessage());
out.println("<br>AfterClose");
out.println("</body></html>");
out.close();
public String getServletInfo() {
return "Title Servlet return Information...";
nullTo run servlets you must have a special server to run them like JRun or Java Web Server visit www.allaire.com to download JRun
You must also download the servlet.jar
java.sun.com
you must configure your CLASSPATH too
CLASSPATH=".:<path>classes12_01.zip":".:<path>servelet.jar"
I'm using Red Hat Linux 6.2 I think this can Help you -
Help ! ! !Oracle 8.1.7, Linux, JDBC problem
We have been troubleshooting a problem with our recently installed Linux (mandrake 8.0) Oracle DB Server. Everything seems to run fine, except JDBC connections. Whenever we connect to the server with one of our Java applications, JSP, Servlet, etc... the first time it works, then all other java apps get:
java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
... also, our connect strings are correct... seems to be a problem with the listener...
this only happens on the linux server and not solaris.
Here is the listener.ora file
# LISTENER.ORA Network Configuration File: /disk1/OraHome1/network/admin/listener.ora
# Generated by Oracle configuration tools.
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC))
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = warf))
(ADDRESS = (PROTOCOL = TCP)(HOST = 216.174.11.57)(PORT = 1521))
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = /disk1/OraHome1)
(PROGRAM = extproc)
(SID_DESC =
(GLOBAL_DBNAME = warf.world)
(ORACLE_HOME = /disk1/OraHome1)
(SID_NAME = warf)
)Also,
If I stop the listener and restart it... it works, but only for the first JDBC connection... ODBC seems uneffected. -
hi,
I have a problem... i would like to fetch some strings from the database using JDBC and create a tree structure using java servlets to be displayed on a browser using html.
Currently i have tried using a hashtable as well as defaultmutabletreenode, both of which grew complicated and did not give the desired results.
Pls help...I tried using both a DefaultMutableTreeNode
containing all the other nodes as child nodes and a
hashtable with a series of internal hashtables -- and
passed it to the servlet displaying the html
l content.
Is there a better/simpler data structure to use in
this case other than a Hashtable and a
DefaultMutableTreeNode?How should we know? You're asking what is better to solve your problem, without saying what your problem is. (Hint: "I can't do this" or "It doesn't work" are not useful problem descriptions.)
If I were doing this, and if I had to build a tree structure in memory before producing HTML from it, I would use DefaultMutableTreeNode. But then I don't know anything about your problem. -
Hi
Could someone tell me how to delete or ammend a specific field in a database through a servlet. I have written a servlet that writes to a database but I need it to ammend or delete a already existing field.
Any help would be appreciated.
By the way I am using jswdk-101 server
Regards
MarkHi
I cant for the life of me get it to ammend to the database although I did manage to get it to delete thanks to the code leukbr gave me. Its not compiling at all for some reason. Although it did compile with leukbr code but it didnt do anything.
This is the error I am getting now.
C:\jswdk-1.0.1\examples\WEB-INF\servlets>javac *.java
ad3.java:85: DataAmmend(int,java.lang.String,java.lang.String,java.lang.String)
in ad3 cannot be applied to (java.lang.String,java.lang.String,java.lang.String,
java.lang.String)
out.println (DataAmmend(ad_id, ad_path, email, categ
ory));
^
1 error
Below is the code for ammending.
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
public class ad3 extends HttpServlet{
private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData rsmd;
private String SQL;
private String str_HTML_Result;
public void init() throws ServletException
String url = "jdbc:odbc:addetails";
String username = "test";
String password = "test";
// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(url, username, password );
catch ( ClassNotFoundException cnfex ) {
System.out.println("Time stamp [JDBC Driver]:" + new Date() +
"Failed to load JDBC/ODBC driver." );
System.out.println(
"Time stamp [JDBC Driver]:" + new Date() +
cnfex.toString());
catch ( SQLException sqlex ) {
System.out.println(
"Time stamp [Connection Problem]:" + new Date() +
"Unable to connect" );
System.out.println(
"Time stamp [JDBC Driver]:" + new Date() +
sqlex.toString());
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
String ad_id = request.getParameter("ADID");
String ad_path = request.getParameter("ADPATH");
String shown = request.getParameter("SHOWN");
String clicked = request.getParameter("CLICKED");
String ratio = request.getParameter("RATIO");
String email = request.getParameter("EMAIL");
String category = request.getParameter("CATEGORY");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Ad Manager Ad Removal Section</title>");
out.println("</head>");
out.println("<body bgcolor=\"#999999\" text=\"#000000\">");
out.println("<div align=\"center\">");
out.println("<font face=\"Arial, Helvetica, sans-serif\" size=\"5\" color=\"#DDDD00\">");
out.println("<b>Banner Manager Ad Removal Section</b></font></div>");
out.println("<br>");
out.println("<hr>");
out.println("<table border=" + "\"" + "0" + "\"" +" width=" + "\"" + "100%" + "\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
if((ad_id!=null) && (ad_path!=null) && (email!=null) && (category!=null)) {//**Is this rignt??**
//**Is this rignt??**
out.println (DataAmmend(ad_id, ad_path, email, category)); //**Is this rignt??**
} //**Is this rignt??**
out.println(getDataTable());
/*============================================================================*/
// Main Page HTML
/*============================================================================*/
out.println("</table>");
out.println("<br>");
out.println("<hr>");
out.println("<br>");
out.println(new Date());
out.println("<form ACTION='http://localhost:8080/examples/servlet/ad3' METHOD = GET>");
out.println("<center><B><font face=\"Arial, Helvetica, sans-serif\" size=\"2\"> Ad ID </B>");
out.println("<input type=text name ='ADID'><br>");
out.println("<B> Email Address </B>");
out.println("<input type=text name ='email'>");
out.println("<B> Category </B>");
out.println("<input type=text name ='category'>");
out.println("<B> Ad Path </B>");
out.println("<input type=text name ='ad_path'><p>");
out.println("<input type=submit value = 'Submit'></p>");
out.println("</form>");
out.println("</Font>");
out.println("<br><br>");
out.println("<center><a href = http://localhost:8080/examples/servlet/ad> <b><font face=\"Arial, Helvetica, sans-serif\" size=\"3\">Click here to add a new banner to the system</b></a><br>");
out.println("</center></body>");
/*============================================================================*/
// Get Ad Details List
/*============================================================================*/
private String getDataTable()
String str_HTML="";
try{
SQL= "SELECT ADDETAILS.ADID, ADDETAILS.ADPATH, ADDETAILS.SHOWN, ADDETAILS.CLICKED, ADDETAILS.RATIO, ADDETAILS.EMAIL, ADDETAILS.CATEGORY ";
SQL= SQL + "FROM ADDETAILS ";
statement = connection.createStatement();
resultSet = statement.executeQuery( SQL );
str_HTML = processResultSet( resultSet );
catch ( SQLException sqlex ) {
System.out.println(
"Time stamp [SQL Problem]:" + new Date() +
sqlex.toString());
return str_HTML;
/*============================================================================*/
// Get Ad Details List
/*============================================================================*/
private String getTable()
String str_HTML="";
try
SQL= "SELECT ADDETAILS.ADID, ADDETAILS.ADPATH, ADDETAILS.SHOWN, ADDETAILS.CLICKED, ADDETAILS.RATIO, ADDETAILS.EMAIL, ADDETAILS.CATEGORY ";
SQL= SQL + "FROM ADDETAILS ";
SQL= SQL + "ADID ADDETAILS.ADID";
statement = connection.createStatement();
resultSet = statement.executeQuery( SQL );
str_HTML = processResultSet( resultSet );
catch ( SQLException sqlex ) {
System.out.println(
"Time stamp [SQL Problem]:" + new Date() +
sqlex.toString());
return str_HTML;
/*============================================================================*/
// Ammending details in database
/*============================================================================*/
public int DataAmmend(int A, String adPath, String email, String category) {
//String str_HTML = "";
int result;
int adId = A;
String aadPath = adPath;
String aemail = email;
String acategory = category;
try {
SQL= "UPDATE ADDETAILS SET ADPATH = '" + aadPath + "', EMAIL = '" + aemail + "' CATEGORY = '" + acategory + "' WHERE ADID = " + adId;
statement = connection.createStatement();
result = statement.executeUpdate( SQL );
catch ( SQLException sqlex ) {
System.out.println("Time stamp [SQL Problem]:" + new Date() + sqlex.toString());
return result;
/*============================================================================*/
// Process Ad Details Listing
/*============================================================================*/
private String processResultSet( ResultSet rs ) throws SQLException {
// position to first record
boolean moreRecords = resultSet.next();
// If there are no records, display a message
if ( ! moreRecords ) {
return null;
Vector cols = new Vector();
Vector rows = new Vector();
try
rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
cols.addElement( rsmd.getColumnName(i));
// get row data
do{
rows.addElement( getNextRow( rs, rsmd ) );
}while ( rs.next() );
catch ( SQLException sqlex ) {
System.out.println("Time stamp [Process Reultset]:" + new Date() +
" Exception in Process Results" );
System.out.println("Time stamp [SQL Problem]:" + new Date() +
sqlex.toString());
String str_HTML_TABLE="";
Enumeration enum_Cols = cols.elements();
Enumeration enum_Rows = rows.elements();
StringBuffer buf = new StringBuffer();
buf.append("<tr><td>");
while (enum_Cols.hasMoreElements())
buf.append(enum_Cols.nextElement()).append(" ");
buf.append("</td></tr><tr><td> </td><tr>");
while (enum_Rows.hasMoreElements())
buf.append("<tr><td>" + enum_Rows.nextElement()).append("</td></tr>");
str_HTML_TABLE = str_HTML_TABLE + buf.toString();
return str_HTML_TABLE;
/*============================================================================*/
// Get each row of the to be processed
/*============================================================================*/
private Vector getNextRow( ResultSet rs,ResultSetMetaData rsmd )throws SQLException{
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i ){
currentRow.addElement( rs.getString( i ) );
return currentRow;
/*============================================================================*/
// Close Database Connection
/*============================================================================*/
public void destroy(){
try{
connection.close();
catch (Exception e){
System.out.println("Problem Closing DB");
} -
Please help!
I have a servlet controller, a javabean for the data and a jsp for the view.
I cannot get the jsp using
<jsp:useBean id="pList" class="bbs.PostListCommand" scope="request" />
to access the bean data
However, when I access the bean in this way
<%@ page import="bbs.PostListCommand" %>
// html
<% bbs.PostListCommand postList = null;
synchronized(session){
postList = (bbs.PostListCommand) session.getAttribute("PostListCommand");
if (postList == null){ %>
<H1>Nothing in request scope to retrieve ....</H1>
<P>
<% }
else{ %>
<TABLE border="1">
// etc
� it works
Does anyone know why the <jsp:useBean> tag does not find the bean
I have installed tomcat 4.18 and set the environmental variables etc.
Directory structure is
E:\Tomcat41\webapps\examples\WEB-INF\jsp for jsp�s
E:\Tomcat41\webapps\examples\WEB-INF\classes\bbs for bean and servlets
Thanks in advance for any help.
ChrisGrayMan - Thanks for your help.
Let me explain my problem in more detail ...
Background:
I have some servlet experience, but I am new to jsp - so sorry if this seems trivial to you ...
I have a book called bitter java by bruce tate from manning.com . I am trying to get the chapter 3 examples to work
There are three files
PostListCommand the bean
PostListController the servlet
PostListResults jsp
And a new test file � PostListResults version 2 with scriptlet code to access the bean.
There are a couple of typos in the downloaded source files, but nothing that causes the main problem of not being able to access the bean data.
Program flow
Servlet instantiates new bean
Bean � gets data from db
Servlet passes bean to jsp with a forward
Jsp outputs data
I have put the files in the directories �
E:\Tomcat41\webapps\examples\WEB-INF\jsp for jsp�s
E:\Tomcat41\webapps\examples\WEB-INF\classes\bbs for bean and servlets
The complete source code for each file is given below.
1 I have checked the db access � that�s ok
2 I have also checked reading the bean data back in from the request scope and printing out the results from within the servlet.- ok
3 I can access the data through a scriptlet (PostListResults version 2), but not with the original PostListResults which uses <jsp:useBean>
thanks in advance, chris
PostListController.java
package bbs;
// Imports
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Import for commands used by this class
import bbs.PostListCommand;
public class PostListController
extends javax.servlet.http.HttpServlet
implements Serializable {
* DoGet
* Pass get requests through to PerformTask
public void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
performTask(request, response);
public void performTask(
HttpServletRequest request,
HttpServletResponse response) {
try {
PostListCommand postList = (bbs.PostListCommand) java.beans.Beans.instantiate(getClass().getClassLoader(),"bbs.PostListCommand");
postList.initialize();
postList.execute();
request.setAttribute("PostListCommand", postList);
ServletContext sc = this.getServletContext();
RequestDispatcher rd =
sc.getRequestDispatcher("/jsp/PostListResults.jsp");
rd.forward(request, response);
} catch (Throwable theException) {
theException.printStackTrace();
PostListCommand.java
package bbs;
import java.io.*;
import java.sql.*;
//import COM.ibm.db2.jdbc.*;
import java.util.*;
* Insert the type's description here.
* Creation date: (07/17/2001 5:07:55 PM)
* @author: Administrator
public class PostListCommand {
// Field indexes for command properties
private static final int SUBJECT_COLUMN = 1;
private static final int AUTHOR_COLUMN = 2;
private static final int BOARD_COLUMN = 3;
protected Vector author = new Vector();
protected Vector subject = new Vector();
protected Vector board = new Vector();
// SQL result set
protected ResultSet result;
protected Connection connection = null;
* execute
* This is the work horse method for the command.
* It will execute the query and get the result set.
public void execute()
throws
java.lang.Exception,
java.io.IOException {
try {
// retrieve data from the database
Statement statement = connection.createStatement();
result =
statement.executeQuery("SELECT subject, author, board from posts");
while (result.next()) {
subject.addElement(result.getString(SUBJECT_COLUMN));
author.addElement(result.getString(AUTHOR_COLUMN));
board.addElement(result.getString(BOARD_COLUMN));
result.close();
statement.close();
} catch (Throwable theException) {
theException.printStackTrace();
* getAuthor
* This method will get the author property.
* Since the SQL statement returns a result set,
* we will index the result.
public String getAuthor(int index)
throws
java.lang.IndexOutOfBoundsException,
java.lang.ArrayIndexOutOfBoundsException {
return (String) author.elementAt(index);
* getBoard
* This method will get the board property.
* Since the SQL statement returns a result set,
* we will index the result.
public String getBoard(int index)
throws
java.lang.IndexOutOfBoundsException,
java.lang.ArrayIndexOutOfBoundsException {
return (String) board.elementAt(index);
* getSubject
* This method will get the subject property.
* Since the SQL statement returns a result set,
* we will index the result.
public String getSubject(int index)
throws
java.lang.IndexOutOfBoundsException,
java.lang.ArrayIndexOutOfBoundsException {
return (String) subject.elementAt(index);
* initialize
* This method will connect to the database.
public void initialize()
throws java.io.IOException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// URL is jdbc:db2:dbname
String url = "jdbc:db2:board";
// URL is jdbc:odbc:bitter3board
String url = "jdbc:odbc:bitter3board";
// connect with default id/password
connection = DriverManager.getConnection(url);
} catch (Throwable theException) {
theException.printStackTrace();
* Insert the method's description here.
* Creation date: (07/17/2001 11:38:44 PM)
* @return int
* @exception java.lang.IndexOutOfBoundsException The exception description.
public int getSize() {
return author.size();
PostListResults.jsp
<HTML>
<HEAD>
<TITLE>Message Board Posts</TITLE>
</HEAD>
<BODY BGCOLOR=#C0C0C0>
<H1>All Messages</H1>
<P>
<jsp:useBean id="postList" class="bbs.PostListCommand" scope="request"></jsp:useBean>
<TABLE border="1">
<TR>
<TD>Subject</TD>
<TD>Author</TD>
<TD>Board</TD>
</TR>
<% for (int i=0; i < postList.getSize(); _i++) { %>
<TR> <TD><%=postList.getSubject(_i) %></TD>
<TD><%=postList.getAuthor(_i) %></TD>
<TD><%=postList.getBoard(_i) %></TD>
</TR>
<% } %>
</TABLE>
<P>
</BODY>
</HTML>
PostListResults.jsp version 2 � with scriplet code instead of useBean
<HTML>
<%@ page import="bbs.PostListCommand" %>
<!-- This file was generated by the chris -->
<HEAD>
<TITLE>Message Board Posts</TITLE>
</HEAD>
<BODY BGCOLOR=#C0C0C0>
<% bbs.PostListCommand postList = null;
synchronized(request){
postList = (bbs.PostListCommand) request.getAttribute("PostListCommand");
if (postList == null){ %>
<H1>Nothing in request scope to retrieve ....</H1>
<P>
<% }
else{ %>
<TABLE border="1">
<TR>
<TD>Subject</TD>
<TD>Author</TD>
<TD>Board</TD>
</TR>
<% for (int i=0; i < postList.getSize(); _i++) { %>
<TR> <TD><%=postList.getSubject(_i) %></TD>
<TD><%=postList.getAuthor(_i) %></TD>
<TD><%=postList.getBoard(_i) %></TD>
</TR>
<% } %>
</TABLE>
<% }
}%>
<P>
goodnight
</BODY>
</HTML> -
Distributed transactions/jdbc problem WL60
Hi
Our company has aworking application running on WLS5.1sp9.
Im in the process of migrating it to WL6.0sp2.
Our domain has 2 clusters each running 2 servers:
1) servlet engines (handling http requests from clients, running servlets
and jsp's)
2) ejb containers (runnigour entities and session beans, working with Oracle
8i database using connection pool and TxDataSource)
The scenario:
- a client request invokes a servlet on one of the servlet engines.
- the servlet opens a jndi context to one of the ejb containers
- the servlet open a transaction on a UserTransaction stub on that ejb.
- then the servlet calls an entity bean using a home interface looked up
using the same context.
- the entity bean uses DataSource lookup in its own servers jndi to rerieve
a connection.
and then i get the following exception:
java.sql.SQLException: No default driver for database type:
jdbc:weblogic:jts
at
weblogic.jdbcbase.t3.Driver.seeIfWeNeedToInferDriverNameAndUrlFrom(Driver.ja
va:456)
at weblogic.jdbcbase.t3.Driver.getAllPropsFrom(Driver.java:255)
at weblogic.jdbcbase.t3.Driver.connect(Driver.java:75)
at weblogic.jdbcbase.jts.Driver.createRemoteConnection(Driver.java:199)
at weblogic.jdbcbase.jts.Driver.connect(Driver.java:134)
at
weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java
:44)
at com.unisfair.util.DBHelper.getConnection(DBHelper.java:43)
the transaction toString() gives:
transaction=(IdHash=7541556,Name = [EJB
UserBeanImpl.generateSessionSuffix()],Xid=2:b53da78d3c1badbb,Status=Active,n
umRepliesOwedMe=0,numRepliesOwedOthers=1,seconds since begin=0,seconds
left=30,activeThread=Thread[ExecuteThread: '8' for queue: 'default',5,Thread
Group for Queue:
'default'],ServerResourceInfo[weblogic.jdbc.jts.Connection]=(state=new,assig
ned=none),SCInfo[ejb2]=(state=active),SCInfo[servlet2]=(state=active),SCInfo
[ejb1]=(state=active),properties=({weblogic.transaction.name=[EJB
UserBeanImpl.generateSessionSuffix()], weblogic.jdbc=t3://10.0.0.31:7007}))
However the error happens on the other ejb server 10.0.0.33:7007
It seems that the jts driver tries to get a remote connection on the server
that coordinates the transaction but uses the deprecated t3 driver.
I hope someone can help us since this problem is a good enough reason for us
not moving on to WL6.0 we also looked at WL6.1 Beta and theres nothing new
about it either.
thanks
Dror Last
Senior Software Engineer
Unisfair Inc.
12 Yad Haruzim St. Tel Aviv 67778 Israel
Tel: +972-3-5373738 Ext. 243
Fax: +972-3-5373731
GSM: +972-55-723710
mailto:[email protected]
http://www.unisfair.com/
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by JDBC_TX ():
In the readme file of Oracle JDBC drivers 8.1.6.0.1 (http://technet.oracle.com/software/tech/java/sqlj_jdbc/files/Readme_01.txt)
it mentioned that it supports "distributed transactions".
As I understand, JDBC transaction is connection based and uses Oracle internal transaction manager. In order to do "distributed transactions", I must have at least two connections open at the same time each to its own database instance. How does the two connections coordinate the transactions? I thought in order to support "distributed transactions", one has to build a higher layer to encapsulate the two connections and therefore coordinate the distributed transactions. Any examples will be welcome.<HR></BLOCKQUOTE>
The two branches of the transaction are coordinated using 2-phase commit.
For samples look under
$ORACLE_HOME/jdbc/demo/samples/oci8/jdbc20-samples/
null -
Hi!
We're using Informix 7 + WL6sp1 + Informix JDBC Driver v2.2. We have a connection
pool and connect to the pool using:
Driver myDriver = (Driver) Class.forName("weblogic.jdbc.pool.Driver").newInstance();
con = DriverManager.getConnection("jdbc:weblogic:pool:poolname");
The problem is as follows:
Every time we modify a stored procedure (DROP ... CREATE ...) our app fails when
trying to use that stored procedure. We have to shut down the server and restart
it in order to keep going.
The stack trace:
java.sql.SQLException: SPL routine(disponibilidad_hot) is no longer valid.
at com.informix.jdbc.IfxSqli.addException(IfxSqli.java, Compiled Code)
at com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java, Compiled Code)
at com.informix.jdbc.IfxSqli.dispatchMsg(IfxSqli.java, Compiled Code)
at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java, Compiled Code)
at com.informix.jdbc.IfxSqli.sendStatementQuery(IfxSqli.java, Compiled
Code)
at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java, Compiled
Code)
at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java, Compiled
Code)
at com.informix.jdbc.IfxResultSet.executeQuery(IfxResultSet.java, Compiled
Code)
at com.informix.jdbc.IfxStatement.executeQueryImpl(IfxStatement.java,
Compiled Code)
at com.informix.jdbc.IfxPreparedStatement.executeQuery(IfxPreparedStatement.java,
Compiled Code)
at weblogic.jdbc.pool.PreparedStatement.executeQuery(PreparedStatement.java,
Compiled Code)
at es.gesfor.bd.ObtenerDatos.ejecutar(ObtenerDatos.java, Compiled Code)
at es.gesfor.servlets.FiltrosServlet.obtenerHoteles(FiltrosServlet.java,
Compiled Code)
at es.gesfor.servlets.FiltrosServlet.doPost(FiltrosServlet.java, Compiled
Code)
at javax.servlet.http.HttpServlet.service(HttpServlet.java, Compiled Code)
at javax.servlet.http.HttpServlet.service(HttpServlet.java, Compiled Code)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java,
Compiled Code)
at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java,
Compiled Code)
at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java,
Compiled Code)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java, Compiled
Code)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled Code)Hi Federico,
It happens because weblogic caches prepred statements.
Though the name of the stored procedure remains the same,
it's a different object from the database point of view, which is
why a mismatch between cache and database occurs.
You may consider setting size of the prepared statement
cache to zero. That should solve the problem. Later, when
the SP code is stabilized, you will be able to turn in on back.
Regards,
Slava Imeshev
"Federico Dios" <[email protected]> wrote in message
news:[email protected]...
>
Hi!
We're using Informix 7 + WL6sp1 + Informix JDBC Driver v2.2. We have aconnection
pool and connect to the pool using:
Driver myDriver = (Driver)Class.forName("weblogic.jdbc.pool.Driver").newInstance();
con = DriverManager.getConnection("jdbc:weblogic:pool:poolname");
The problem is as follows:
Every time we modify a stored procedure (DROP ... CREATE ...) our appfails when
trying to use that stored procedure. We have to shut down the server andrestart
it in order to keep going.
The stack trace:
java.sql.SQLException: SPL routine(disponibilidad_hot) is no longer valid.
at com.informix.jdbc.IfxSqli.addException(IfxSqli.java, CompiledCode)
at com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java, CompiledCode)
at com.informix.jdbc.IfxSqli.dispatchMsg(IfxSqli.java, CompiledCode)
at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java, CompiledCode)
at com.informix.jdbc.IfxSqli.sendStatementQuery(IfxSqli.java,Compiled
Code)
at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java,Compiled
Code)
at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java,Compiled
Code)
at com.informix.jdbc.IfxResultSet.executeQuery(IfxResultSet.java,Compiled
Code)
atcom.informix.jdbc.IfxStatement.executeQueryImpl(IfxStatement.java,
Compiled Code)
atcom.informix.jdbc.IfxPreparedStatement.executeQuery(IfxPreparedStatement.jav
a,
Compiled Code)
atweblogic.jdbc.pool.PreparedStatement.executeQuery(PreparedStatement.java,
Compiled Code)
at es.gesfor.bd.ObtenerDatos.ejecutar(ObtenerDatos.java, CompiledCode)
ates.gesfor.servlets.FiltrosServlet.obtenerHoteles(FiltrosServlet.java,
Compiled Code)
at es.gesfor.servlets.FiltrosServlet.doPost(FiltrosServlet.java,Compiled
Code)
at javax.servlet.http.HttpServlet.service(HttpServlet.java,Compiled Code)
at javax.servlet.http.HttpServlet.service(HttpServlet.java,Compiled Code)
atweblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
Compiled Code)
atweblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletCo
ntext.java,
Compiled Code)
atweblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java
Compiled Code)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java,Compiled
Code)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, CompiledCode) -
Can anyone please help me with pointing to the right direction on webapplications.
I have a table in the database that returns 50K rows when running a query. I have been reading through some books and forums, SDN including that a correct way to access the database is through the Business tier EJB session beans and JPA and access these objects from Servlets. I understand that and I have an example that works using paging so I do not need to send all 50K records at once. My question is, the resultset retrieves entity objects and I have to create data transfer objects for each one of them to send to the GWT client? Doesn't it mean I have twice as much objects in the memory at a time to compare with accessing database through JDBC from Servlets directly? In the later case I wouldn't have any entity objects and occupy less memory? Is it completely wrong idea?
Thanksmambo_jumbo wrote:
Without their superpowers some of them are still not serializable for GWT.
Never mind,
Thanks for answer.I don't understand what the problem is here.
Dod you have a problem with making them Serializable? They have to be Serializable if you want to make them arguments to remote methods anyway.
Maybe you are looking for
-
Problem with .css for Spry menu
Hi, I am having a problem with the Spry menu I have created and edited. All looks great in the Design view of Photoshop however under the Live view or opened using a browser the menu reverts to a list of hyperlinks! I have checked the .css link but w
-
Mac Pro 15in A few weeks old! black screen when trying to boot windows 7Ult
I have installed Windows 7 ultimate on my mac book pro 15 in, which is brand new! I have OSX 6.2 and Bootcamp 3.0.1.. I installed everything, and updated drivers. Then I closed out of Windows and everything seemed to be working fine. Until I try to b
-
XY graph response slows with dashed plot
I have an xy graph displaying multiple plots. I find that if at least one of the plots uses a dashed line as the line type, and that this plot has zero values displayed, then the response of the graph slows significantly. Redraws seem to take 5 to 10
-
Spooling large data using UTL_FILE
Hi Everybody! While spooling out data into a file using UTL_FILE package I am unable spool the data The column data has a size of 2531 characters The column 'source_where_clause_text' has very large data. Its not giving any error but the external tab
-
IDOC Process code...
Hi,, If know the port thru which the Idoc's is processed, how can i know the process code for this port...? Regrds, M...