JDBC Servlet Problem
Hi,
I am trying to write a servlet to do a simple query against a database, however I am getting an "ERROR 405 - Resource not allowed".
I am getting nothing appearing in my webservers or the jdbc log, so I don't have a stack trace to show you all.
Any help would be appreaciated!!
Code Below (certain data removed for security):
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.sql.ResultSet.*;
import java.util.*;
import java.util.Arrays;
public class Mitch extends HttpServlet
private Connection connection;
private Statement statement;
public static ArrayList Array = new ArrayList();
public void init( ServletConfig config ) throws ServletException
try
String username = "xxxxxxx";
String password = "xxxxxxx";
Class.forName("com.ibm.db2.jcc.DB2Driver");
String dbURL = "jdbc:db2://IP ADDRESS AND PORT/DIR";
Properties conProps = new Properties();
conProps.setProperty( "user", username );
conProps.setProperty( "password", password );
connection = DriverManager.getConnection( dbURL, conProps );
statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
catch( Exception exception )
exception.printStackTrace();
throw new UnavailableException( exception.getMessage() );
}//end init
protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" );
out.println( "<HTML>\n<HEAD>" );
String sqlQuery;
try
sqlQuery = "SELECT h5_cpu_usr FROM ps_h5_cpu_fs_ap1 WHERE h5_dttm_stamp BETWEEN '2005-2-20 00:00:00.00000' AND '2005-2-20 23:00:00.000000'";
ResultSet resultSet = statement.executeQuery( sqlQuery );
out.println( "<TITLE> Servlet DB Test by Mitch </TITLE>" );
out.println( "</HEAD>" );
out.println( "<BODY>" );
out.println( "<P>This is a test to connect to a database, execute a simple SELECT and display the results below." );
out.println( "<br>\n<br>" );
Integer intObject;
while ( resultSet.next() )
intObject = new Integer( resultSet.getInt( 1 ) );
Array.add( intObject );
resultSet.close();
for( int i = 0; i < Array.size(); i++)
out.println(Array.get(i));
out.close();
}//end try
catch ( SQLException sqlEx )
sqlEx.printStackTrace();
out.println( "<TITLE>ERROR</TITLE>" );
out.println( "<HEAD>" );
out.println( "<BODY><P>An error occurred.<br>Contact Mitch!" );
out.println( "</P></BODY></HTML>" );
out.close();
}//doPost end
public void destroy()
try
statement.close();
connection.close();
catch( SQLException sqlEx )
sqlEx.printStackTrace();
}//end destroy
}//end Class
Thank you both for your replies
1. Yes I did.
2 See below
I found some sample code that I adapted to my code. I removed the init( ) method and used a doGet ( ) to call my doPost ( ) method.
The servlet now works!
Except for one thing...
It doesn't seem to be threading!
I did a simple test where two different users attempted to use the servlet at the same time, the results simply added to each other. The current query I am doing is one that returns approximately 100 rows and 1 column of 2-digit integers.
For example:
User 1 runs the servlet, output is:
12 45 56 66 65 23 06 03 34 56 78
User 2 runs the servlet after User 1, output is:
12 45 56 66 65 23 06 03 34 56 78 12 45 56 66 65 23 06 03 34 56 78
User 1 runs servlet again, after User 2, output is:
12 45 56 66 65 23 06 03 34 56 78 12 45 56 66 65 23 06 03 34 56 78 12 45 56 66 65 23 06 03 34 56 78
I hope this illustrates my problem clearly.
Also, I checked the database to see how many connections were open -- the servlet opens a NEW connection for EVERY query. These connections do not die until I kill my WebApp (WebLogic). It truely is a messy situation.
Any help would be appreaciated for this servlet newbie.
Thanks in advance.
New Code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.sql.ResultSet.*;
import java.util.*;
import java.util.Arrays;
public class Mitch extends HttpServlet
public static ArrayList Array = new ArrayList();
Connection connection;
Statement statement;
String username = "xxxxxxx";
String password = "xxxxxxx";
protected synchronized void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
doPost ( request, response );
protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
//HttpSession session = request.getSession(true);
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" );
out.println( "<HTML>\n<HEAD>" );
String sqlQuery;
//if(session.isNew())
try
Class.forName("com.ibm.db2.jcc.DB2Driver");
String dbURL = "jdbc:db2://xx.xx.xx.xx:yyyyy/zzzzzzz";
connection = DriverManager.getConnection( dbURL, username, password );
statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
sqlQuery = "SELECT h5_cpu_usr FROM ps_h5_cpu_fs_ap1 WHERE h5_dttm_stamp BETWEEN '2005-2-20 00:00:00.00000' AND '2005-2-20 23:00:00.000000'";
ResultSet resultSet = statement.executeQuery( sqlQuery );
out.println( "<TITLE> Servlet DB Test by Mitch </TITLE>" );
out.println( "</HEAD>" );
out.println( "<BODY>" );
out.println( "<P>This is a test to connect to a database, execute a simple SELECT and display the results below." );
out.println( "<br>\n<br>" );
Integer intObject;
while ( resultSet.next() )
intObject = new Integer( resultSet.getInt( 1 ) );
Array.add( intObject );
resultSet.close();
for( int i = 0; i < Array.size(); i++)
out.println(Array.get(i));
out.close();
}//end try
catch ( SQLException sqlEx )
sqlEx.printStackTrace();
out.println( "<TITLE>ERROR</TITLE>" );
out.println( "<HEAD>" );
out.println( "<BODY><P>An error occurred.<br>Contact Mitch!" );
out.println( "</P></BODY></HTML>" );
out.close();
catch( Exception exception )
exception.printStackTrace();
throw new UnavailableException( exception.getMessage() );
//else
// out.println( "<h1>This indicates an old session</h1>" );
}//doPost end
public void destroy()
try
statement.close();
connection.close();
catch( SQLException sqlEx )
sqlEx.printStackTrace();
}//end destroy
}//end Class
Similar Messages
-
Oracle/JDBC servlet problem
My code and error message are found below:
Why can't I resolve the variable "val"?
Thanks
package moreservlets;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet used to test the use of packages. */
public class TitleQueries extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Connecting to Database";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@pc840:1521:orcl", "scott", "tiger");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select * from emp");
while (rset.next()) {
String val = rset.getString(1);
catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
out.println(ServletUtilities.headWithTitle(title) +
"<body bgcolor=\"#FDF5E6\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h1 align=\"center\">" + val + "</h1>\n" +
"</body></html>");
C:\J2ee\moreservlets>javac -d "C:\Program Files\Apache Tomcat 4.0\webapps\ROOT\W
EB-INF\classes" TitleQueries.java
TitleQueries.java:46: cannot resolve symbol
symbol : variable val
location: class moreservlets.TitleQueries
"<h1 align=\"center\">" + val + "</h1>\n" +
^
1 errorYou're declaring the variable "val" inside your while loop, which gives the variable scope inside that loop. As soon as the loop finishes executing, that variable will cease to be.
Instead, declare the variable outside the while loop, and you can access it later on without any problems...
String val = null;
while (rset.next()) {
val = rset.getString(1);
}Just fyi though, in the current setup, you're only going to end up with the very last value retrieved from teh database, since you're overwriting val each time you loop through the resultset. If you want to keep all the variables, maybe use an ArrayList? -
Jdbc-servlet help!!!!!!!!
excuse my english.
hey folks, i got this problem:
i`m trying to do a simple servlet that`s throw a html with a result, but i always got this error:
java.lang.NullPointerException
at ConsultaServlet.doPost(ConsultaServlet.java:45)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
THIS IS THE CODE I HAVE:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HolaServlet 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");
con =DriverManager.getConnection("jdbc:odbc:MS Access Database");
}catch(Exception e) {
System.err.println(e);
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 Demo" +
"</title>");
out.println("</head>");
out.println("<body>");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from empleados");
out.println("<UL>");
while(rs.next()) {
out.println("<LI>" + rs.getString("nombre"));
out.println("</UL>");
rs.close();
stmt.close();
} catch(SQLException e) {
out.println("An SQL Exception was thrown.");
} catch(IOException e) {
System.err.println("An IOException was thrown.");
out.println("</body>");
out.println("</html>");
out.close();
public void destroy(){
try{
con.close();
}catch(SQLException e) {
Can someone tell me what i`m doing wrong.
THANK.Hi,
I have intalled the Javawebserver2.0
Its been installed on C:\javawebserver2.0.
After this I have set the autoexec.bat path as
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\ORAWIN95\bin;c:\Oracle\Ora81\bin;"C:\ProgramFiles\Oracle\jre\1.1.7\bin";c:\j2sdk1.4.2_04\bin;c:\JavaWebServer2.0\bin;c:\Jsdk2.0\bin
rem - By Windows 98 Network for Netware Upgrade - c:\windows\odihlp.exe
set classpath=.;c:\j2dsk1.4.2_04\jre\lib;c:\j2dsdk1.4.2_04\lib;c:\j2sdk1.4.2_04\bin;c:\JavaWebServer2.0\lib;c:\Jsdk2.0\lib
rem -;c:\jsdk2.1\src ;c:\jsdk2.1\lib;c:\Jsdk2.0\src
After doing this I wrote my first servlet program in the servlets directory of javawebserver2.0 saved and when I went to compile its not compiling throwing an error showing that it is unable to locate all the servlet packages. So in I thought might be there are 2 things one is either I have not imported javax.servlet.* and javax.servlet.httpServlet.* package, but I had included it, the next thing was to check the autoexec.bat path. I included in that javawebserver2.0 path. Now first I am not able to compile the servlet program. Can you help me with it.
I had downloaded jsdk2 from net and have given its path also in the autoexec but nothing is happening. I am using the following package to write and develop Java programs "j2sdk1.4.2_04". Can you explain to where I am going wrong. Please its a bit urgent.
Following is the program:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class helloWorld extends HttpServlet
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head><Title>Hello World</title></head>");
out.println("<body><big>Hello World</big>");
out.println("</body>");
out.println("</html>");
Help!!!!!!!! -
MSSQLServer jdbc connect problem on ODI 11G R2
I have a MS SQL Server jdbc connect problem on ODI 11G R2 / Windows server 2008 64 bits.
Tried, one by one, all versions of Microsoft drivers.
Sqljdbc4.jar copied to : %appdata%\odi\oracledi\userlib\
The Topology connect syntax is :
driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
URL : jdbc:sqlserver://<host>:1433
=> All the topology tests end with time-outs.
Installed 10G ODI.
Works with 1.4 java and sqljdbc.jar version 2 jdbc driver.
Times out with version 3 and/or Sqljdbc4.jar + JAVA_HOME & ODI_JAVA_HOME set to 1.6 path.
also tried, with no success (time-outs) on either 10g or 11g :
com.inet.tds.TdsDriver
jdbc:inetdae7://<host>:1433?database=<DB>
same results for :
net.sourceforge.jtds.jdbc.Driver
jdbc:jtds:sqlserver://<host>:1433
Any suggestions for a fix?
Many thanks in advance.Hello,
ODI (11g) Studio is certified on Windows 32 bit only, not on 64bit.
However you may still install it and configure ODI Studio to run with a 32 bit java.
Details pls see Master Note For ODI 11g Install Issues And Questions (Doc ID 1214428.1).
To connect to SQL Server:
# Check and make sure the authentication mode of your Microsoft SQL Server Server is set to "SQL Server and Windows" or "Mixed", otherwise Oracle Data Integrator (ODI) is unable to connect to the database.
# Before you create the Oracle Data Integrator (ODI) Dataserver in Topology Manager > Physical Architecture, stop all ODI processes, and place the JDBC Driver file in the ODI's userlib and "/drivers" folder.
For ODI Studio (Local No Agent)
%APPDATA%\odi\oracledi\userlib
%APPDATA% is the Windows Application Data directory for the user (usually C:\Documents and Settings\<user>\Application Data).
Standalone Agent
ODI_HOME\oracledi\agent\drivers
Note: If you decide to use the DataDirect driver that comes with ODI 11g install/ embedded in ODI 11g
weblogic.jdbc.sqlserver.SQLServerDriver
Then you don't need to worry about this step.
# Make sure that the database is the default database of the user account employed by ODI for connection, and that the password is correct.
# Verify (in your Microsoft SQL Server Server network configuration) that TCP/IP has been enabled on port 1433.
For more details see How To Set Up JDBC Driver Connections For The Microsoft SQL Server For ODI (Doc ID 423914.1)
If you try sqljdbc.jar, you need to configure ODI_JAVA_HOME to jdk1.5
sqljdbc4.jar, jdk1.6 (since ODI 11g requires jdk1.6, I'd suggest sqljdbc4.jar)
More see Compatibility Matrix For Java Machines And JDBC Drivers Used With ODI (Doc ID 807235.1)
Hope that helps other people who run into this,
Edited by: user742480 on Apr 4, 2011 12:06 PM -
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 -
Mildet connect to oracle DB using servlet problem ,help please
hi guys i have a problem am tring to connect my midlet to databse through midlet but i don`t know what is the problem so far the midlet already connect to my servlet url but the servlet cant read the parameters to open the connection for database
my servlet code
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.io.*;
import java.net.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.text.*;
* @author freddy
public class getconnection extends HttpServlet {
Statement statement;
ResultSet rs=null;
String bstr=null;
String bstr1=null;
String bstr2=null;
public void init()
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet getConnection</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet getConnection at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
doPost(request,response);
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
DataInputStream in = new DataInputStream(
(InputStream)request.getInputStream());
String sid = in.readUTF();
String user = in.readUTF();
String pwd = in.readUTF();
// "jdbc:oracle:thin:@localhost:1521"+": "+sid
String message = message = "Name:"+bstr+" telephone:"+bstr1+" burthday:"+bstr2;
try {
connect(sid,user, pwd);
message += "100 ok connected";
} catch (Throwable t) {
message += "200 " + t.toString();
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
in.close();
out.close();
out.flush();
private void connect(String sid, String user,String pwd)
throws Exception {
// Establish a JDBC connection to the MYSQL database server.
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:"+sid,user,pwd);
System.out.print("connected");
try{
statement =conn.createStatement();
rs=statement.executeQuery(" Select*from WOH.P_DEMGRAPHICS where P_ID='P1000 '");
catch(SQLException e)
System.err.print(e);
try{
while (rs.next()) {
bstr=rs.getString(2);
bstr1=rs.getString(3);
bstr2=rs.getString(4);
statement.close();
catch (SQLException e) {
//bstr += e.toString();
System.err.println(e);
System.exit(1);
// Establish a JDBC connection to the Oracle database server.
//DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
//Connection conn = DriverManager.getConnection(
// "jdbc:oracle:thin:@localhost:1521:"+db,user,pwd);
// Establish a JDBC connection to the SQL database server.
//Class.forName("net.sourceforge.jtds.jdbc.Driver");
//Connection conn = DriverManager.getConnection(
// "jdbc:jtds:sqlserver://localhost:1433/"+db,user,pwd);
* Returns a short description of the servlet.
public String getServletInfo() {
return "Short description";
// </editor-fold>
}Midlet code
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
* @author freddy
public class testOrcl extends MIDlet implements CommandListener {
protected String url;
private String username;
private Display display;
private Command exit = new Command("EXIT", Command.EXIT, 1);;
private Command connect = new Command("Connect", Command.SCREEN, 1);
private TextField tb;
private Form menu;
private TextField tb1;
private TextField tb2;
DB db;
public testOrcl() throws Exception
display=Display.getDisplay(this);
url="http://localhost:8084/getConnection/getconnection";
public void startApp() {
displayMenu();
public void displayMenu()
menu= new Form("connect");
tb = new TextField("Please input database: ","",30,
TextField.ANY );
tb1 = new TextField("Please input username: ","",30,
TextField.ANY);
tb2 = new TextField("Please input password: ","",30,
TextField.PASSWORD);
menu.append(tb);
menu.append(tb1);
menu.append(tb2);
menu.addCommand(exit);
menu.addCommand(connect);
menu.setCommandListener(this);
display.setCurrent(menu);
public void pauseApp() {
public void destroyApp(boolean unconditional) { }
public void commandAction(Command command, Displayable screen) {
if (command == exit) {
destroyApp(false);
notifyDestroyed();
} else if (command == connect) {
db = new DB(this);
db.start();
db.connectDb(tb.getString(),tb1.getString(),tb2.getString());
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.lang.*;
* @author freddy
public class DB implements Runnable {
testOrcl midlet;
private Display display;
String sid;
String user;
String pwd;
public DB( testOrcl midlet)
this.midlet=midlet;
display=Display.getDisplay(midlet);
public void start()
Thread t = new Thread(this);
t.start();
public void run()
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(midlet.url);
c.setRequestProperty(
"User-Agent","Profile/MIDP-2.1, Configuration/CLDC-1.1");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os =
(DataOutputStream)c.openDataOutputStream();
os.writeUTF(sid.trim());
os.writeUTF(user.trim());
os.writeUTF(pwd.trim());
os.flush();
os.close();
// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
showAlert(sb.toString());
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
/* This method takes input from user like db,user and pwd and pass
to servlet */
public void connectDb(String sid,String user,String pwd) {
this.sid = sid;
this.user = user;
this.pwd = pwd;
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
Comment out process request or rewrite & move it to a position after you read the parameters and connect to the db. Decide where you want to write to the output stream. Also, you have some superfluous casting.
I take it that you are using netbeans? If you debug and step through the code you will get an idea of the flow. The steps should be, midlet connects with POST, doPost is called, server reads parameters, server opens connection, executes query, releases/closes connection, and writes a response to the midlet.
Some notes about the connect method; The scope of rs may cause problems. It is unlike you will have a valid result set if you have a problem with create statement or execute. Take a look at connection pooling and be mindful how the connections are opened, used, and closed; put all the important cleanup operations in a finally. Remove system.exit from your servlet. Actually I would suggest limiting the scope of all your vars;
If you store the username, password, and sid on the midlet, you may have trouble updating the installation base if you need to change the values for any reason. Also, you have clients which contain your database u/p, susceptible to snooping and decompilation. Use the servlet to abstract the db from the client. And use a datasource (with connection pooling) for obtaining connections to db. -
STRUTS - JDBC connection problem
im using tomcat 5.5.9, jdk 1.5, oracle database...
� have a project in struts...
my project works with my compiler with no problem...
*i setup tomcat on C:\jakarta-tomcat-5.5.9
and � made these setting for tomcat:
� added these strings to my CLASSPATH
--C:\jakarta-tomcat-5.5.9\common\lib\servlet-api.jar
--C:\jakarta-tomcat-5.5.9\common\lib\jsp-api.jar
after � deployed my project under tomcat there was a "classes12.zip" file under this path:
C:\jakarta-tomcat-5.5.9\webapps\BILGISU\WEB-INF\lib
� changed it to class.jar
also � have other .jars under the same path above.
these jars are:
classes12.jar
commons-beanutils.jar
commons-collections.jar
commons-dbcp.jar
commons-digester.jar
commons-fileupload.jar
commons-lang.jar
commons-logging.jar
commons-pool.jar
commons-validator.jar
jakarta-oro.jar
jdbc2_0-stdext.jar
struts.jar
struts-legacy.jar
THE PROBLEM IS:
my index page is a "login" page..
i can open the login page under tomcat.
but when � enter the username and password, page says it is wrong username or password although these are true parameters...
i think i still have a connection problem but � dont know how to solve...
MY SEARCHES SAYS:
you have to reconfigure "C:\jakarta-tomcat-5.5.9\conf\server.xml" like that:
<Resource name="jdbc/myoracle"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:[email protected]:1521:mysid"
username="scott"
password="tiger"
maxActive="20"
maxIdle="10"
maxWait="-1"/>
Resource name="jdbc/myoracle" ->HERE WHAT IS "myoracle"??? DOES IT BELONG TO MY PROJECT?
you have to reconfigure "C:\jakarta-tomcat-5.5.9\conf\web.xml" like that:
<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>jdbc/myoracle</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
will i write this to my web.xml
and what is "auth=Container" here???????
thanks in advance
yasinONE MORE QUESTION
Im defining the datasource in my "struts-config.xml"
do i have to define them again in "tomcat/conf/server.xml" ... -
JDBC + SERVLET: inserting text data to access file from Html form
Hi everybody !
I'm trying to insert text data from my html form to access database using servlet and jdbc technologies.
The problem that I'm that the data is TEXT, but not the English language !!!
So my access db file gets - ???????? symbols instead the real text.
This is the form line that sending data to my servlet:
<form
method="POST"
ACTION=http://localhost:8080/servlet/myServlet enctype="text/html">
And this is servlet line that defines response content:
res.setContentType( "text/html" );
What can I do to get in access db file the right text format and not a ???????? symbols.
Maybe I must to ad some <meta ...> , but where ?You're dealing with Unicode, I'd guess, and not ASCII.
I guess I'd have two questions:
(1) Is the character encoding on your pages set properly for the language you're trying to use?
(2) Does Access handle Unicode characters?
Access isn't exacly a world-class database. (If it was, there'd be no reason for M$ to develop SQL Server.) I'd find out if it supports other character sets. If not, you'll have to switch to a more capable database that does. - MOD -
JSP + JDBC + MySql Problem (Tomcat 4.1)
I'm completely helpless... whenever I try to retrieve stuff from the db (using a jsp page), I get errors that don't even make sense.
out.println(stmt.executeQuery("SELECT * FROM newsTbl WHERE articleID = 1").getString("articleTitle"));if I try doing the above, I get a "ServletException : Before start of result set" error that supposedly occurred at this line of the generated servlet:
if (pageContext != null) pageContext.handlePageException(t);---------------
If i try this:
ResultSet rsSec = stmt.executeQuery("SELECT * FROM newsSecTbl");
rsSec.beforeFirst(); //<-- Even if I don't have this line the result does not change
out.println(rsSec.next());
while (rsSec.next()) { ... }I the while loop is never initiated, because rsSec.next() is false... kind of weird if you ask me, I even put two entries into the table to make sure the cursor wasnt at the first record and saying there was no second one (which would have been right if there were only one record).
I would be very grateful if someone could help me out with this. I've never done any db programming with Java yet, so I dont have a clue what Im doing. By the way, I'm using MySql (indicated in the title) and the server was running and available when I ran the above code.
Cheers,
TomYou can't do this:
out.println(stmt.executeQuery("SELECT * FROM newsTbl WHERE articleID = 1").getString("articleTitle"));The ResultSet you get back is a database cursor that doesn't point to the first row yet. The correct idiom is:
String sql = "SELECT * FROM newsTbl WHERE articleID = 1";
ResultSet result = stmt.executeQuery(sql);
String articleTitle = "";
while (result.next())
title = result.getString("articleTitle");
result.close();
stmt.close();If you've never done DB programming before, I'd recommend that you click on the Tutorials link to the left and go through the JDBC tutorial carefully. You'll save yourself a lot of grief.
Another good idea would be to separate out all your database code into at least one separate object, independent of the servlet. That way you can test and develop it off to the side until it's 100% solid. Then your servlet can simply instantiate one and use it. All your problems from that point forward will be servlet issues, because you'll know that your database code is working. - MOD
See if that works better. - MOD -
Hello, I'm getting this error when trying to make a connection with MySQL:
Internal Servlet Error:
org.apache.jasper.JasperException: Unable to compile class for JSPNote: sun.tools.javac.Main has been deprecated.
C:\tomcat\work\localhost_8080\_0002fdb_0002ejspdb_jsp_10.java:62: Undefined variable or class name: DriverManager
conn = DriverManager.getConnection("jdbc:mysql:numbers", "username", "password");
^
1 error, 1 warning
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:282)
at org.apache.jasper.servlet.JspServlet.doLoadJSP(JspServlet.java:612)
at org.apache.jasper.servlet.JasperLoader12.loadJSP(JasperLoader12.java:146)
at org.apache.jasper.servlet.JspServlet.loadJSP(JspServlet.java:542)
at org.apache.jasper.servlet.JspServlet$JspServletWrapper.loadIfNecessary(JspServlet.java:258)
at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:268)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:429)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:500)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.tomcat.core.ServletWrapper.doService(ServletWrapper.java:405)
at org.apache.tomcat.core.Handler.service(Handler.java:287)
at org.apache.tomcat.core.ServletWrapper.service(ServletWrapper.java:372)
at org.apache.tomcat.core.ContextManager.internalService(ContextManager.java:806)
at org.apache.tomcat.core.ContextManager.service(ContextManager.java:752)
at org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java:213)
at org.apache.tomcat.service.TcpWorkerThread.runIt(PoolTcpEndpoint.java:416)
at org.apache.tomcat.util.ThreadPool$ControlRunnable.run(ThreadPool.java:501)
at java.lang.Thread.run(Thread.java:536)
Here's the code I'm using:
<%
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
java.sql.Connection conn;
conn = DriverManager.getConnection("jdbc:mysql:numbers", "username", "password");
%>
If anyone knows how to fix this, I'd appreciate any help!Hi,
Three things:
1. I presume numbers refers to the prot you are accesaing mysql - i tend to use default 3306.
2. If there are problems recognising DriverManagaer are you importing java.sql.*; I'm sure you are.
3. I think the sun.tools.javac.Main error relates to the tools version that you are using, although I would not guarantee this. The tools.jar in later versions of tomcat is twice the size of earlier versions and you have to ensure this is the version that your application is checking for. A quick test for this is to put the newer version(size 74k) into WEB-INF \lib directory where an application looks first for complied java files.
best,
kev
ps If I'm wrong completely, let me know as I am watching this topic -
JDBC / Servlet / ": Io exception: SO Exception was generated"
Hi,
i am trying to write a simple Servlet program that would access oracle 9i database and display the names in the "emp" table in the form of a html page.
I am using tomcat 4.0, jdk1.2.2, oracle 9i, windows 98.
I am getting this exception as the outoput of the program:
"Io exception: SO Exception was generated "
The input of the program will be through a html file, with a form that will ask the user for his/her name(this has got nothing to do with the logic of the program.. just for the sake of using a html form):
HTML file:
<html>
<head>
<title>First Aplet</title>
</head>
<body>
<FORM METHOD=GET ACTION="http://localhost:8080/Hello">
What is your name?
<input type=text name="name"><p>
<input type=submit>
</form>
</body>
</html>
The code for the servlet class is as follows:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String name = req.getParameter("name");
res.setContentType("text/html");
out = res.getWriter();
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection(
"jdbc:oracle:thin:@","scott","tiger");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * from EMP");
out.println("<HTML><HEAD><TITLE>EMp Table Details for "+name+"</TITLE></HEAD>");
out.println("<BODY>");
out.println("");
out.print("<TABLE>\n");
try{
ResultSetMetaData rsmd = rs.getMetaData();
int numcols = rsmd.getColumnCount();
out.print("<TR>");
for(int i = 1;i<=numcols;i++)
out.print("<TH>"+rsmd.getColumnLabel(i));
out.print("</TR>\n");
while(rs.next()){
out.print("<TR");
for(int i=1;i<=numcols;i++){
out.print("<TD>");
Object obj = rs.getObject(i);
if(obj!=null)
out.print(obj.toString());
else
out.print(" ");
out.print("</TR>\n");
catch(SQLException e){
out.print("SQLEXception : "+e.getMessage());
out.println("</TABLE>");
out.println("</BODY></HTML>");
catch(SQLException e){
out.println("SQLEXception caught: " + e.getMessage());
public String getServletInfo(){
return "A servlet that knows the name of the person to whom it is saying hello";
can anyone help?
thanks..
KdevRayaThe getMetaVersion is not the problem, it works ok.
the problem is the second connection
conn = DriverManager.getConnection ("jdbc:oracle:thin:@database",info);
This is exactly as it is illustrated in the "JDBC Developer?s Guide and R
Reference" from oracle for release 9.2 Part No. A96654-01 page 3-8
//import packages and register the driver
import java.sql.*;
import java.math.*;
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
//specify the properties object
java.util.Properties info = new java.util.Properties();
info.put ("user", "sys");
info.put ("password", "change_on_install");
info.put ("internal_logon","sysdba");
//specify the connection object
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@database",info);" -
ClassNotFoundException in running jdbc servlet
hi
i've wrote a servlet to connect to my Teradata db but when i run it
on tomcat i get this java lang exeption:
ClassNotFoundException: com.ncr.teradata.TeraDriver
the thing is that the connection and sql code work on an application withoput any problems, but when i try to use on a servlet i get this exception...
why??
maybe i have to change some settings of tomcat.. ?
hope someone can say smth about
thanks!You need to tell Tomcat where to find the JDBC driver, remember that the Tomcat Classpath overrides the JDK classpath. For example, in Tomcat 3.x you need to put the driver in tomcat-installation/lib/common
Just be sure that the JDBC is a jar file, Tomcat cannot read zip files.
Hope this help. -
App Server 8.1 JDBC Connection problem
Dear Expert,
Cu are using Sun Java System Application Server Enterprise Edition 8.1. Cu created one jdbc connection pool and datasource. They are called
jdbc/RM
From the App Server Admin Console -> Connection Pool, cu can "Ping" the database via the connection pool.
Cu did the configuration on web.xml and sun-web.xml
web.xml
<resource-ref>
<description>Oracle Database Connection - Rawmart</description>
<res-ref-name>jdbc/RM</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
sun-web.xml
<resource-ref>
<res-ref-name>jdbc/RM</res-ref-name>
<jndi-name>jdbc/RM</jndi-name>
</resource-ref>
In customer class,
220: protected void initDataSource() throws NamingException {
221: initContext = new InitialContext();
222: envContext = (Context) initContext.lookup("java:comp/env");
223: String dataSource = rConfigObject.getConfigValue("DATASOURCE");
224: rDataSource = (DataSource) envContext.lookup(dataSource);
225: }Exception occurs on line no. 222 already.
From server.log, we get
================
#|2005-06-03T11:36:11.562+0800|WARNING|sun-appserver-ee8.1|javax.enterprise.system.stream.err|_ThreadID=10;|
javax.naming.NameNotFoundException: No object bound for java:comp/env [Root exception is java.lang.NullPointerException]
at com.sun.enterprise.naming.java.javaURLContext.lookup(javaURLContext.java:161)
at com.sun.enterprise.naming.SerialContext.lookup(SerialContext.java:288)
at javax.naming.InitialContext.lookup(InitialContext.java:351)
at com.ns.DBObject.initDataSource(DBObject.java:222)
at com.ns.DBObject.connectPool(DBObject.java:213)
at com.ns.DBObject.<init>(DBObject.java:91)
at com.ns.DBObject.getInstance(DBObject.java:122)
at com.ncharter.NCContextListener.contextInitialized(NCContextListener.java:28)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4010)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4525)
===============
Do you have any ideas on this problem? Thanks.
Regards,
AngusTry asking the Customer to fire up the JNDI browser in the admin console and try to browse the JNDI tree.
What class is the InitialContext.lookup() happening in? Is that getting executed in the servlet class or a standalone client?
thanks. -
Hi all,
Thanks for the warning this is my problem:
exception
org.apache.jasper.JasperException: Exception in JSP: /DAO.jsp:16
13:
14: Class.forName("oracle.jdbc.driver.OracleDriver");
15:
16: conn = DriverManager.getConnection("jdbc:oracle:thin://PC280631275888:1521:XE","vincenzom86","xxx");
17:
18: Statement st = conn.createStatement();
19:
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:451)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:355)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
root cause
javax.servlet.ServletException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
The Connection descriptor used by the client was:
localhost:1521:orcl
i've change also all the sid name in the listner.ora and tnsnames.ora with XE that is the SID of my DB.
VincenzoIf XE is a SID specify the following url
jdbc:oracle:thin:@PC280631275888:1521:XE
If XE is a service specify the following url
jdbc:oracle:thin:@//PC280631275888:1521/XE -
AS904: JDBC classpath problem in OC4J instance
Hi,
I want to run an ADF Faces web app in AS 904 (WAR contains all JAR incl. JDBC JARs). It does not work because the the application uses a newer version of the JDBC JARs than the version provided with AS904. The OC4J instance seems to load the older JDBC version instead of the JDBC version provided with the WAR.
The classpath of the AS904 OC4J instance defined in application.xml does not include any JDBC JARs.
This fact seems to be the root of all the trouble!
Is there a way to change the classpath for the JDBC JARs of my OC4J instance without affecting other OC4J instances?
MarkusThanks Avi!
I can' solve my problem because the CLASSPATH of the OC4J-instance has a fixed prefix definition. Changing the CLASSPATH in application.xml oder with a cmd switch like -cp "my class path" only affects the CLASSPATH behind the prefix.
The prefix is definds in the manifest file of the oc4j.jar like this:
lib/ejb.jar lib/servlet.jar lib/ojsp.jar lib/jndi.jar lib/
jdbc.jar iiop.jar iiop_gen_bin.jar lib/jms.jar lib/jta.jar lib/jmxri
.jar lib/javax77.jar lib/javax88.jar ../../opmn/lib/ons.jar ../../op
mn/lib/optic.jar ../../lib/dms.jar ../../dms/lib/dms.jar lib/connecto
r.jar lib/cos.jar lib/jsse.jar ../../oracle/lib/jsse.jar lib/jnet.ja
r lib/jcert.jar lib/activation.jar lib/mail.jar ../../javavm/lib/jasp
er.zip ../../lib/xmlparserv2.jar ../../oracle/lib/xmlparserv2.jar lib
/jaxp.jar lib/jaas.jar jazn.jar ../../jdbc/lib/classes12dms.jar ../..
/oracle/jdbc/lib/classes12dms.jar ../../jdbc/lib/nls_charset12.jar ..
/../oracle/jdbc/lib/nls_charset12.jar jaxb-rt-1.0-ea.jar ../../soap/
lib/soap.jar ../../webservices/lib/wsserver.jar ../../webservices/lib
/wsdl.jar ../../rdbms/jlib/aqapi.jar lib/jem.jar ../../javacache/lib/
cache.jar lib/http_client.jar ../../jlib/jssl-1_1.jar ../../oracle/jl
ib/jssl-1_1.jar ../../jlib/repository.jar ../../oracle/jlib/repositor
y.jar lib/jaasmodules.jar ../../sqlj/lib/runtime12ee.jar ../../sqlj/l
ib/translator.jar lib/crimson.jar
As you can see, the JDBC lib is loaded with this settings before my CLASSPATH seetings!
I bet changing this manifest file affects Oracle support. ;-)
In the end, my J2EE web application does not run on a J2EE compliant Oracle AS 904!
Thanks,
Markus
Maybe you are looking for
-
How can I set 'Adobe PDF printer' as one of my printer choices?
I've given it half an hour. Can't seem to figure out how I can set 'Adobe PDF printer' as one of my printer options. I'm not sure if I need to download an Adobe file, and what folder I might need to place it in, and if I also need to add a specific d
-
Need upload a PDF document and send it as attachment
hi all, i need help. i need to upload a standard pdf file and send it as attachment .. every time i use the func. module Gui_upload it corrupts the pdf file. is there any func. module that can serve my purpose. please help .. usefull suggestion wi
-
Maybe 1 out of 10 maybe youtube videos works. My favorites, including music videos were working just fine and now only a couple are working. I cleared my cache, restarted the computer, updated flash and none worked. Installed chrome, didn't work. I d
-
Viewing CLOB data in sql developer
In SQL Developer 1.1, if CLOB data was returned from a query, you could place your mouse over the column and get most of it. But in 1.2, all you get is "(CLOB) <some data> ...", and nothing else. Is there something I need to set?
-
BUG? - Btrieve Gateway with Memo's in Crystal Report XI - Connector-Error
Hello, we are using Crystal Report XI R2 with the Btrieve-Gateway (Pervasive 8 - 10) crdb_p2bbtrv.dll (12.0.0.683) p2bbtrv.dll (12.0.0.683). Now we have big problems when we use tables with memo-fields (lvar or longvarchar) in a report. If we run the