Servlet and Database.
Hello everyone.
I am planning to build a client server application. Client is a J2ME application which sends some data using HTTP POST to a servlet to acess Mysql database. I need to create a Server application in Java which should notify the user on the server that a data has been received and that the database has been updated. How do i do it? please help. Thanks in advance
I have done the client application,.I can use the j2me application to send data to mysql database through servlet. I need to create the server application now which can also send data to the database using servlet. I use httpconnection class in j2me. But it is not working in ma servlet application. Does any one know how to creat e a server application which can access a servlet in orde to save data onto a database. Reply.
Similar Messages
-
Servlet and Database Connectivity
Hi,
I have got a basic question. I am connecting to a database through a servlet and displaying a table. What I need to do is have three buttons at the bottom of the table like "ADD", "DELETE" "MODIFY". I am wondering how I can add buttons to the HTML page through the servlet, select a row and click on one of the buttons to MODIFY/DELETE and how to capture the actions of each button when clicked like when "ADD" button is clicked it should pass control to a servlet "add.java". If i plan to include a javascript how can i call from the servlet, is there a way. If anyone could throw me some light or atleast point me in the right direction that would be great.
Thanks
Chakyou can even use buttons!
HTML:
<input type="submit" name="add" value="Add">
<input type="submit" name="modify" value="Modify">
<input type="submit" name="delete" value="Delete">
Servlet:
String addButton = req.getParameter("add");
String modifyButton = req.getParameter("modify");
String deleteButton = req.getParameter("delete");
So when the add-Button is clicked, addButton equals to "add", modifyButton==null and deleteButton==null, and vice versa -
This is my first database program using servlet. Also I use ECS to create the HTML document.
I accept data from a HTML page and display on the screen as well as writing to a TABLE (in instantDB)
Do I have to have the database connection in INIT() method ?
-------------Here's the code ---------------------------------------------------
public class work2_db extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String dbName = "db";
String tableName = "survey";
Connection conn = null;
Statement stmt = null;
System.out.print("\nLoading JDBC driver...\n\n");
try {
// InstantDB JDBC driver
Class.forName("com.lutris.instantdb.jdbc.idbDriver");
// MS Access, use default JDBC-ODBC driver
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
try {
System.out.print("Connecting to " + dbName + " database...\n\n");
// InstantDB
String url = "jdbc:idb:" + dbName;
// InstantDB, specify the configuration file name in URL
conn = DriverManager.getConnection(url + ".prp");
// MS Access
//conn = DriverManager.getConnection(url);
System.out.println("Connected to and created database " + dbName);
System.out.print("Accessing new " + tableName + " table...\n\n");
stmt = conn.createStatement();
} catch (SQLException se) {
se.printStackTrace();
System.exit(1);
int id=0;
//Go to the last record of the result set to get the next Survey ID
String queryString = "SELECT * FROM " + tableName ;
ResultSet rset = stmt.executeQuery(queryString);
while (rset.next()) {
id = rset.getInt("surveyid");
id++; // This is the Survey ID for this new survey.
rset.close();
int service[] = {0,0,0,0,0,0};
int level[] = {0,0,0,0,0};
Body body = new Body();
Html html = new Html()
.addElement(new Head()
.addElement(new Title("Survey Conformation")))
.addElement(body);
body.addElement(new H1("Thank you! Your Survey is accepted."));
body.addElement(request.getParameter("salutation") + " " +
request.getParameter("firstname") + " " +
request.getParameter("lastname"))
.addElement(new BR());
body.addElement(request.getParameter("company"))
.addElement(new BR());
body.addElement(request.getParameter("street"))
.addElement(new BR());
body.addElement(request.getParameter("city") + " " +
request.getParameter("state") + " " +
request.getParameter("postal"))
.addElement(new BR());
body.addElement(request.getParameter("country"))
.addElement(new BR());
body.addElement("Email: " + request.getParameter("email"))
.addElement(new BR())
.addElement(new BR());
body.addElement("You Travelled with us to : " +
request.getParameter("destination"))
.addElement(new BR());
body.addElement("You used our following Services : ");
body.addElement(new BR());
String values[] = request.getParameterValues("service");
if (values != null) {
UL list = new UL();
for (int i = 0; i < values.length; i++) {
list.addElement(new LI(values));
// setup category 1 feedback
if (values[i] != null)
service[i] = 1;
body.addElement(list);
body.addElement(new BR());
body.addElement("Your satisfaction level : ");
body.addElement(request.getParameter("level") + " " +
request.getParameter("good") + " " +
request.getParameter("better") + " " +
request.getParameter("best") + " " +
request.getParameter("very poor quality") + " " +
request.getParameter("none"))
.addElement(new BR());
body.addElement("You said we Can improve our Service as follows: " +
request.getParameter("comments"));
out.println(html.toString());
//set up category level feed back
if (request.getParameter("good") != null)
level[1] = 1;
else if (request.getParameter("better") != null)
level[2] = 1;
else if (request.getParameter("best") != null)
level[3] = 1;
else if (request.getParameter("very poor quality") != null)
level[4] = 1;
else if (request.getParameter("none") != null)
level[5] = 1;
//Now write the collected data into the database
String insertString = "INSERT intO" + tableName+
id + "," + service[1] + "," + service[2] + "," + service[3] + "," +
+ service[4] + "," + service[5] + "," + service[6] + "," +
+ level[1] + "," + level[2] + "," + level[3] + "," +
+ level[4] + "," + level[5] ;
stmt.close();
conn.close();
-------------------------Compile Errors ---------------------------------------------------------------------------------
I am getting following error for the exception handling. Can someone help me !!! PLEASEHi JDKPSSH,
Do I have to have the database connection in INIT() method ?not mandatory to have it in init() ( not INIT() ) method.
I am getting following error for the exception handling. Can someone help me !!! PLEASE Check out by putting the following statements in try block
stmt.close();
conn.close();otherwise you get a compile time error.
unreported exception java.sql.SQLException; must be caught or declared to be thrown
Thanks,
Sanath Kumar. -
Servlets and database connectivity
I have connected my html webpage to a database in mysql. The servlet takes the answer of the radio button and compare it with the answer stored in the database.
Is it possible to have two queries in one servlet?? Because when the servlet is run on the webpage it opens another html tellin the user if the answer was correct/incorrect. On that same page I want it to display the next question and set of radio buttons.
Help!I have connected my html webpage to a database in
mysql. The servlet takes the answer of the radio
button and compare it with the answer stored in the
database.
Is it possible to have two queries in one servlet??
Because when the servlet is run on the webpage it
opens another html tellin the user if the answer was
correct/incorrect. On that same page I want it to
display the next question and set of radio buttons.
Help!You may need to declare couple different Statement's or preparedStatements's depending wich one you use or you can just use the same ResultSet twice.
Can't help you anymore without seeing your code -
Please help with servlet and database!!
Hello,
i first created a servlet that generated an html page and printed out the parameters of a user's username when they logged in. example, "Welcome user" and it worked fine...
i inserted a database into my site that validates the username and password, and ever since i did that in dreamweaver, when a user logs in sucessfully, it returns the servlet page like its supposed to, only that it says "Welcome null" instead of "Welcome John." pretty strange, huh!? can anyone please help? thanks!Check whether the username textfield name has changed or not. Also print the code over here so that we can check the code.
-
Using database connection in a servlet and get errors after 8 hours
Hey,
I'm running a poker script using applet/servlets and it works great. But for some reason about about 8 hours that database layer stops working. At first I thought it was the connections to mySQL that were timing out (because im using connection pooling) but after turning pooling off (I now create the connection each time) I'm still seeing that same error (I can create a connection but when I do an action ex. like a select statment I get an error). What i'm wondering could it be that the driver I load with Class.forName() some how unloads it's self after x amount of time not being used? Not sure if that is it but if anyone could give me some insight that would be great. The Error i recieve is below:
INFO: Database Event:DatabaseController: Error executing database query.
ERROR: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Software caused connection abort: recv failed
STACKTRACE:
java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:104)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:144)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:172)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1839)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2288)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2784)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1531)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1622)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2370)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2297)
at com.mysql.jdbc.Statement.executeQuery(Statement.java:1183)
at com.softnet.database.DatabaseController.executeDatabaseQuery(DatabaseController.java:190)
at com.softnet.games.GameServer.validateUser(GameServer.java:438)
at com.softnet.games.GameServer.handleData(GameServer.java:113)
at com.softnet.network.HttpConnectionThread.run(HttpServletListener.java:191)
** END NESTED EXCEPTION **
I know the query is good because it works all other times just not after about 8 hours.
--Z3r0CooLHey,
Thanks for the responces. For the connection pooling I would open 5 connections and keep them open. So i though maybe after 8 hours after not being used they would timeout. Thats why i turned off conection pooling and create a new connection each time. Anyways i'll post the code below incase i made a mistake somewhere.
package com.softnet.database;
/************************ DatabaseControler **************************/
import java.sql.*;
import java.util.*;
import com.softnet.database.DatabaseConnectionPool;
import com.softnet.database.DatabaseSettings;
public class DatabaseController
implements DatabaseListener
//Used to make sure the database driver is loaded
private boolean databaseDriverState = false;
//Used to store a database connection
private Connection databaseConnection = null;
//If to user connection pooling or not
private boolean useConnectionPooling = false;
//Used to hold the connection pool varible
private DatabaseConnectionPool connectionPool = null;
//Used to store database settings
private DatabaseSettings databaseSettings;
//Used to hold the DatabaseController listeners
private List databaseControllerListeners = new ArrayList();
//min number of connections for connection pool
private int minNumberOfConnections = 1;
//max number of connections for connection pool -1 is unlimited
private int maxNumberOfConnections = -1;
//DatabaseController Constructors
public DatabaseController(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
public DatabaseController(DatabaseSettings databaseSettings, boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
this.databaseSettings = databaseSettings;
this.useConnectionPooling = useConnectionPooling;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
if(useConnectionPooling == true)
connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
connectionPool.addDatabaseListener(this);
else
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
public DatabaseController() {}
//Database Settings Get/Set
public DatabaseSettings getDatabaseSettings()
return databaseSettings;
public void setDatabaseSettings(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
//Connection Pooling Get/Set
public boolean getConnectionPooling()
return useConnectionPooling;
public void setConnectionPooling(boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
this.useConnectionPooling = useConnectionPooling;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
if(useConnectionPooling == true)
if(connectionPool == null)
connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
connectionPool.addDatabaseListener(this);
else
if(connectionPool != null)
connectionPool.destroyConnections();
connectionPool.removeDatabaseListener(this);
connectionPool = null;
//Return if there connected
public boolean isConnected()
boolean isConnected;
if(databaseConnection != null)
isConnected = true;
else
isConnected = false;
return isConnected;
//Used to connect to database or get a connection for the connection pool
public void connect()
if(databaseDriverState == false)
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//If we dont have a current connection, make one
if(databaseConnection == null && databaseDriverState == true)
if(useConnectionPooling == false)
try
databaseConnection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch (SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error connecting to database. \nERROR: " + sqle.getMessage());
databaseConnection = null;
else
databaseConnection = connectionPool.getConnection();
//Used to disconnect from the database or give back the connection to the connection pool
public void disconnect()
if(databaseConnection != null)
if(useConnectionPooling == false)
try
//Close DB Connection
databaseConnection.close();
catch(SQLException ignore) {}
finally
databaseConnection = null;
else
connectionPool.returnConnection(databaseConnection);
databaseConnection = null;
public ResultSet executeDatabaseQuery(String sSQL)
ResultSet databaseResult = null;
if(databaseConnection != null)
try
Statement databaseStatement = databaseConnection.createStatement();
databaseResult = databaseStatement.executeQuery(sSQL);
catch(SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error executing database query.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
return databaseResult;
public int executeDatabaseUpdate(String sSQL)
int rowsAffected = -1;
if(databaseConnection != null)
try
Statement databaseStatement = databaseConnection.createStatement();
rowsAffected = databaseStatement.executeUpdate(sSQL);
catch(SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error executing database update.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
return rowsAffected;
//Used to load the Database Driver
private boolean loadDatabaseDriver(String databaseDriver)
boolean driverLoaded;
if(databaseDriver.equals("") == false)
try
//Load Database Driver
Class.forName(databaseDriver).newInstance();
driverLoaded = true;
catch (Exception e)
//Raise event
raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + e.getMessage());
driverLoaded = false;
else
driverLoaded = false;
return driverLoaded;
//Wrap the DatabaseConnectionPool Error to the DatabaseController
public void databaseEventOccurred(DatabaseEvent de)
raiseDatabaseEvent(de.getErrorMessage());
//Event Handling Code
//Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
public synchronized void addDatabaseListener(DatabaseListener databaseControllerListener)
databaseControllerListeners.add(databaseControllerListener);
//Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
public synchronized void removeDatabaseListener(DatabaseListener databaseControllerListener)
databaseControllerListeners.remove(databaseControllerListener);
//Used to send the raise event to the listeners
private synchronized void raiseDatabaseEvent(String databaseError)
DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
Iterator listeners = databaseControllerListeners.iterator();
while(listeners.hasNext())
DatabaseListener listener = (DatabaseListener) listeners.next();
listener.databaseEventOccurred(databaseEvent);
/********************* DatabaseConnectionPool **************/
package com.softnet.database;
import java.io.*;
import java.sql.*;
import java.util.*;
import com.softnet.database.*;
import com.softnet.database.DatabaseSettings;
public class DatabaseConnectionPool
//min number of connections
private int minNumberOfConnections = 1;
//max number of connections -1 is unlimited
private int maxNumberOfConnections = -1;
//Store the connections
protected Hashtable databaseConnections = null;
//Database Info
protected DatabaseSettings databaseSettings;
//to hold Driver state
private boolean databaseDriverState = false;
//To hold connection checker
private DatabaseConnectionCheck connectionChecker = null;
//Used to hold the DatabaseConnectionPool listeners
private List databaseConnectionPoolListeners = new ArrayList();
public DatabaseConnectionPool(DatabaseSettings databaseSettings, int minNumberOfConnections, int maxNumberOfConnections)
this.databaseSettings = databaseSettings;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
//Load Driver
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//Create connection
createConnections();
public DatabaseConnectionPool(int minNumberOfConnections, int maxNumberOfConnections)
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
//Database Settings Get/Set
public DatabaseSettings getDatabaseSettings()
return databaseSettings;
public void setDatabaseSettings(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
//Driver State Get
public boolean getDatabaseDriverState()
return databaseDriverState;
public void createConnections()
if(databaseDriverState == false)
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//Create all connections and load the minimum in the Hashtable
if(databaseConnections == null)
if(databaseDriverState == true && minNumberOfConnections != 0)
databaseConnections = new Hashtable();
for(int i = 0; i < minNumberOfConnections; i++)
try
databaseConnections.put(DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword()), Boolean.FALSE);
catch(SQLException sqle)
//Problem break loop and destroy any connections
destroyConnections();
//Raise event
raiseDatabaseEvent("DatabaseConnectionPool: Error creating database connections. \nERROR: " + sqle.getMessage());
break;
//If no connection check exists create one
if(connectionChecker == null)
connectionChecker = new DatabaseConnectionCheck(this);
connectionChecker.start();
public Connection getConnection()
Connection connection = null;
boolean errorWithConnection = false;
Enumeration connections = databaseConnections.keys();
synchronized (databaseConnections)
while(connections.hasMoreElements())
errorWithConnection = false;
connection = (Connection) connections.nextElement();
Boolean state = (Boolean) databaseConnections.get(connection);
//If connection is not used, use it.
if(state == Boolean.FALSE)
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
// Update the Hashtable to show this one's taken
databaseConnections.put(connection, Boolean.TRUE);
// Return the connection
return connection;
//All connections being used check to max to see if we can make a new one
if(maxNumberOfConnections == -1 || maxNumberOfConnections > databaseConnections.size())
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
databaseConnections.put(connection, Boolean.TRUE);
return connection;
//If not connections free and max connections reached wait for a free connection
return getConnection();
public void returnConnection(Connection connection)
boolean errorWithConnection = false;
//Make sure connection still works
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
databaseConnections.put(connection, Boolean.FALSE);
public void destroyConnections()
Connection connection = null;
if(databaseConnections != null)
//Close all connections
Enumeration connections = databaseConnections.keys();
while (connections.hasMoreElements())
connection = (Connection) connections.nextElement();
try
connection.close();
catch(SQLException ignore) {}
//Free up hashtable
databaseConnections = null;
private boolean loadDatabaseDriver(String databaseDriver)
boolean driverLoaded;
if(databaseDriver.equals("") == false)
try
//Load Database Driver
Class.forName(databaseDriver);
driverLoaded = true;
catch (ClassNotFoundException cnfe)
//Raise event
raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + cnfe.getMessage());
driverLoaded = false;
else
driverLoaded = false;
return driverLoaded;
//Event Handling Code
//Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
public synchronized void addDatabaseListener(DatabaseListener databaseConnectionPoolListener)
databaseConnectionPoolListeners.add(databaseConnectionPoolListener);
//Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
public synchronized void removeDatabaseListener(DatabaseListener databaseConnectionPoolListener)
databaseConnectionPoolListeners.remove(databaseConnectionPoolListener);
//Used to send the raise event to the listeners
private synchronized void raiseDatabaseEvent(String databaseError)
DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
Iterator listeners = databaseConnectionPoolListeners.iterator();
while(listeners.hasNext())
DatabaseListener listener = (DatabaseListener) listeners.next();
listener.databaseEventOccurred(databaseEvent);
class DatabaseConnectionCheck extends Thread
private DatabaseConnectionPool connectionPool;
DatabaseConnectionCheck(DatabaseConnectionPool connectionPool)
this.connectionPool = connectionPool;
public void run()
try
while(true)
//check threads every 30 seconds
this.sleep(300000);
if(connectionPool.databaseConnections != null)
Connection connection = null;
Enumeration connections = connectionPool.databaseConnections.keys();
synchronized (connectionPool.databaseConnections)
while(connections.hasMoreElements())
connection = (Connection) connections.nextElement();
Boolean state = (Boolean) connectionPool.databaseConnections.get(connection);
//If connection is not used, use it.
if(state == Boolean.FALSE)
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
connectionPool.databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(connectionPool.databaseSettings.getDatabaseURL(), connectionPool.databaseSettings.getUserName(), connectionPool.databaseSettings.getUserPassword());
catch(SQLException sqle)
connection = null;
// Update the Hashtable with new connection if its not null
if(connection != null)
connectionPool.databaseConnections.put(connection, Boolean.FALSE);
catch(InterruptedException ignored) {}
Basicly the why it works is the connection pool hold the database connections. When the user needs a connection they use the database controller to request a connection (By create a instance and called the connect() method) and the connection is either created or grabed from the connection pool. After the user is done with the connection they call the disconnect() method which closes the connection or returns it to the connection pool.
--Z3r0CooL -
Servlets and JSPs stored within Oracle 8i
Folks,
Does anyone know when Oracle will release support to servlets
and Java Server Pages in Oracle8i for Linux? Everything in the
database, including my HTML pages!!
Best Regards,
Luis Claudio R. da Silveira
TRE/GO
nullAlright well looks like I'm stuck now.
This seems more like a PL\SQL question though. If I want to return 2 or more values do I use function or a procedure? here's the code I made:
CREATE OR REPLACE FUNCTION sign_in(username VARCHAR(20), userpassword VARCHAR(20))
RETURN NUMBER IS id_num NUMBER, user_type VARCHAR(1);
BEGIN
SELECT * INTO id_num, user_type
FROM ID_MASTER idm, PERSON prs
WHERE USERNAME = username
AND USER_PASSWORD = userpassword
AND idm.ID_NUM = prs.ID_NUM;
RETURN id_num, user_type;
END;
now according to Oracle this is an invalid function. But the error message doesn't say much. Basically I want to pass 2 parameters to use for a query and return 2 variables from the result of the query. Am I suppose to use a procedure?
If I pass paramters do which string do I use to prepareCall: "{ ? = CALL sign_in (?, ?) }" or do I use the "{ CALL sign_in (?, ?) }"
But my problem right now is how to make the proper stored procedure. I'd be very much obliged to anyone who can give a sample. Thank you all for your time! -
Reading a properties file in a servlet and passing its contents to a JSP pa
Hi all,
I'm totally new to Servlet pgmg n JSP. Please can ne1 tell how to read a simple properties file (in a servlet) and pass its contents to a JSP page.Actually the reason is to fill a combo box in a JSP page with the contents of a properties file.If calling a servlet for the same is d best way to do that, plz can ne1 tell me :
1> whether to override the doPost method in the servlet in which to read d file using FileInputStream
2> Putting the contents in an array and then how to pass this array to the JSP page.
Thanks,
deepthy.I'm using a properties file to let my web application know what the name of the database is. I'm using an abstract class GeneralDao which will be extended by all the DAO's (Data Access Objects or java classes containing SQL statements).
Here's the code :
protected Connection getDatabaseConnection()
throws Melding
Connection dbconn = null;
ResourceBundle resBundle;
try
Class.forName("com.mysql.jdbc.Driver").newInstance();
resBundle = ResourceBundle.getBundle("gcoConfig");
String dbConnectie = resBundle.getString("databaseconnection");
gcoLogger.debug("lezen databaseconnection in resourceBundle " );
dbconn = DriverManager.getConnection(dbConnectie);
} catch (InstantiationException exc)The ResourceBundle is used to read the properties file, named gcoConfig.properties.
With the getString() command I read the content of the string named databaseconnection.
The gcoConfig.properties file is placed inside the folder C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\gco\WEB-INF\classes
The GeneralDao is placed in the folder C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\gco\WEB-INF\classes\org\gertcuppens\cluifDao.
So this class is placed some folder below the WEB-INF\classes folder of gcoConfig.properties.
And the content of the properties file is just one line :
databaseconnection=jdbc:mysql://localhost/cluif
If you want to let the JSP know what's inside the properties file, wrap the content in a Javabean, put it in the request or even the session and pass the control to the JSP. -
Help With Integrating Servlet and JSP Page?
Hello There
--i made jsp page that contain name and description fields and add button
--and i made servlet that contain the code to insert name and description in the database
--and i want to make that when the user hit the add button
-->the entered name and description is sent to the servlet
and the servlet sent them to database?
here's what i 've done:
the jsp code:
<html:html locale="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Categories Page
</title>
<html:base/>
</head>
<body style="background-color: white">
<form action="jpage.jsp" method="get">
<h1>
<center>
categories Operations
</center>
</h1>
<h3>
<label>Name</label>
<input type="text" name="name" value="" size="10" />
<label>Description</label>
<input type="text" name="description" value="" size="10" />
<input type="submit" value="Add" name="button" />
</h3>
</form>
</body>
</html:html>the servlet code:
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
class NewServlet1 extends HttpServlet{
Connection conn;
private ServletConfig config;
public void init(ServletConfig config)
throws ServletException{
this.config=config;
public void service (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(true);
res.setContentType("text/html");
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/struts", "root", "");
PreparedStatement ps;
ps = conn.prepareStatement ("INSERT INTO categories (Name, Description) VALUES(?,?)");
ps.setString (1, "aa");
ps.setString (3, "bb");
ps.executeUpdate();
ps.close();
conn.close();
}catch(Exception e){ e.getMessage();}
public void destroy(){}
}The JSP Code:
<html:html locale="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Categories Page
</title>
<html:base/>
</head>
<body style="background-color: white">
<form action="actionServlet.do?action=Additem" method="*post*">
<h1>
<center>
categories Operations
</center>
</h1>
<h3>
<label>Name</label>
<input type="text" name="name" value="" size="10" />
<label>Description</label>
<input type="text" name="description" value="" size="10" />
<input type="button" value="Submit">
</h3>
</form>
</body>
</html:html>The Servlet Code:
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
public class NewServlet1 extends HttpServlet implements SingleThreadModel {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
doPost(request,response);
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
String action = request.getParameter("action"); // action = "Additem"
if (action.equals("Additem")) {
String name = request.getParameter("name");
String description = request.getParameter("description");
RequestDispatcher reqDisp = null;
try{
Connection conn;
PreparedStatement ps;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/struts", "root", "");
ps = conn.prepareStatement ("INSERT INTO categories (Name, Description) VALUES(?,?)");
ps.setString (1, name);
ps.setString (3, description);
ps.executeUpdate();
ps.close();
conn.close();
reqDisp= request.getRequestDispatcher("./index.jsp");
reqDisp.forward(request, response);
catch (Exception ex){
System.out.println("Error: "+ ex);
}The web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>NewServlet1</servlet-name>
<servlet-class>NewServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>NewServlet1</servlet-name>
<url-pattern>/NewServlet1</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>com.test.servlet.NewServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app> -
How to include a jsp file in servlets and javabeans
Hi to all..I have a jsp file which contains some database connections and I would like to include in that file in my servlets and javabeans.What coding can i use?Can show me sample coding.
Hi to all..I have created a javabean storing the
database connections. How do i include and call that
bean in my servlet and javabeans?Can pls show me some
sample coding?I am new to servlets and beans.The same way you do with normal Java Classes. If you are new to Java, I suggest you go to http://java.sun.com/docs/books/tutorial/index.html and look through the first couple of tutorials.
As a note, it is best to put all your objects into packages, especially if you use JDK 1.4 or higher. -
JSP Servlet and convert the result set of an SQL Query To XML file
Hi all
I have a problem to export my SQL query is resulty into an XML file I had fixed my servlet and JSP so that i can display all the records into my database and that the goal .Now I want to get the result set into JSP so that i can create an XML file from that result set from the jsp code.
thisis my servlet which will call the jsp page and the jsp just behind it.
//this is the servlet
import java.io.*;
import java.lang.reflect.Array;
import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;
public *class *Campaign *extends *HttpServlet
*private* *final* *static* Logger +log+ = Logger.+getLogger+(Campaign.*class*.getName());
*private* *final* *static* String +DATASOURCE_NAME+ = "jdbc/SampleDB";
*private* DataSource _dataSource;
*public* *void* setDataSource(DataSource dataSource)
_dataSource = dataSource;
*public* DataSource getDataSource()
*return* _dataSource;
*public* *void* init()
*throws* ServletException
*if* (_dataSource == *null*) {
*try* {
Context env = (Context) *new* InitialContext().lookup("java:comp/env");
_dataSource = (DataSource) env.lookup(+DATASOURCE_NAME+);
*if* (_dataSource == *null*)
*throw* *new* ServletException("`" + +DATASOURCE_NAME+ + "' is an unknown DataSource");
} *catch* (NamingException e) {
*throw* *new* ServletException(e);
protected *void *doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
Connection conn = *null*;
*try* {
conn = getDataSource().getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select post_id,comments,postname from app.posts");
// out.println("Le résultat :<br>");
ArrayList <String> Lescomments= *new* ArrayList<String>();
ArrayList <String> Lesidentifiant = *new* ArrayList<String>();
ArrayList <String> Lesnoms = *new* ArrayList <String>();
*while* (rs.next()) {
Lescomments.add(rs.getString("comments"));
request.setAttribute("comments",Lescomments);
Lesidentifiant.add(rs.getString("post_id"));
request.setAttribute("id",Lesidentifiant);
Lesnoms.add(rs.getString("postname"));
request.setAttribute("nom",Lesnoms);
rs.close();
stmt.close();
*catch* (SQLException e) {
*finally* {
*try* {
*if* (conn != *null*)
conn.close();
*catch* (SQLException e) {
// les paramètres sont corrects - on envoie la page réponse
getServletContext().getRequestDispatcher("/Campaign.jsp").forward(request,response);
}///end of servlet
}///this is the jsp page called
<%@ page import="java.util.ArrayList" %>
<%
// on récupère les données
ArrayList nom=(ArrayList)request.getAttribute("nom");
ArrayList id=(ArrayList)request.getAttribute("id");
ArrayList comments=(ArrayList) request.getAttribute("comments");
%>
<html>
<head>
<title></title>
</head>
<body>
Liste des campagnes here i will create the xml file the problem is to display all rows
<hr>
<table>
<tr>
</tr>
<tr>
<td>Comment</td>
<td>
<%
for( int i=0;i<comments.size();i++){
out.print("<li>" + (String) comments.get(i) + "</li>\n");
}//for
%>
</tr>
<tr>
<td>nom</td>
<td>
<%
for( int i=0;i<nom.size();i++){
out.print("<li>" + (String) nom.get(i) + "</li>\n");
}//for
%>
</tr>
<tr>
<td>id</td>
<td>
<%
for( int i=0;i<id.size();i++){
out.print("<li>" + (String) id.get(i) + "</li>\n");
}//for
%>
</tr>
</table>
</body>
</html>
This is how i used to create an XML file in a JSP page only without JSP/SERVLET concept:
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
// Identify a carriage return character for each output line
int iLf = 10;
char cLf = (*char*)iLf;
// Create a new empty binary file, which will content XML output
File outputFile = *new* File("C:\\Users\\user\\workspace1\\demo\\WebContent\\YourFileName.xml");
//outputFile.createNewFile();
FileWriter outfile = *new* FileWriter(outputFile);
// the header for XML file
outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
try {
// Define connection string and make a connection to database
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/SAMPLE","app","app");
Statement stat = conn.createStatement();
// Create a recordset
ResultSet rset = stat.executeQuery("Select * From posts");
// Expecting at least one record
*if*( !rset.next() ) {
*throw* *new* IllegalArgumentException("No data found for the posts table");
outfile.write("<Table>"+cLf);
// Parse our recordset
// Parse our recordset
*while*(rset.next()) {
outfile.write("<posts>"+cLf);
outfile.write("<postname>" + rset.getString("postname") +"</postname>"+cLf);
outfile.write("<comments>" + rset.getString("comments") +"</comments>"+cLf);
outfile.write("</posts>"+cLf);
outfile.write("</Table>"+cLf);
// Everything must be closed
rset.close();
stat.close();
conn.close();
outfile.close();
catch( Exception er ) {
%>Please state your problem that you are having more clearly so we can help.
I looked at your code I here are a few things you might consider:
It looks like you are putting freely typed-in comments from end-users into an xml document.
The problem with this is that the user may enter characters in his text that have special meaning
to xml and will have to be escaped correctly. Some of these characters are less than character, greater than character and ampersand character.
You may also have a similiar problem displaying them on your JSP page since there may be special characters that JSP has.
You will have to read up on how to deal with these special characters (I dont remember what the rules are). I seem to recall
if you use CDATA in your xml, you dont have to deal with those characters (I may be wrong).
When you finish writing your code, test it by entering all keyboard characters to make sure they are processed, stored in the database,
and re-displayed correctly.
Also, it looks like you are putting business logic in your JSP page (creating an xml file).
The JSP page is for displaying data ONLY and submitting back to a servlet. Put all your business logic in the servlet. Putting business logic in JSP is considered bad coding and will cause you many hours of headache trying to debug it. Also note: java scriptlets in a JSP page are only run when the JSP page is compiled into a servlet by java. It does not run after its compiled and therefore you cant call java functions after the JSP page is displayed to the client. -
Using a single connection for jsp, servlets and classes
Hi! I'm building a web site that uses JSP, Servlets and some classes. I use database access in all my pages. I want to open a connection and use it for all the pages while the user is in my site, so I don't need to open a connection with every new jsp or servlet page. My software must be capable of connection with various databases, like SQLServer, Oracle, Informix, etc... so the solution must not be database (or OS or web server) dependant.
Can you help me with this? Some ideas, links, tips? I'll REALLY appreciate your help.
Regards,
Raul Medinause an initialiation servlet with pooled connection which can be accessed as sesssion object.
Abrar -
Servlet with Database Access!!!
Hi !!!!
I have deployed HelloServlet with Oracle Application Server 4.0.8.1.
Now I want to connect from Servlet to Oracle8i 8.1.5.
But, when I try to deploy a Servlet with Database Access, I receive the next:
"Get operation not allowed"
The URL used is:
http://host.domain:port/virtual_path/class_name
The servlet was compiled using the Sun's jdk from command line. There wasn't compilation errors.
I run a simple application with database access from command line without problems.
The drivers and JDBC libraries are operating for this simple application.
Any help will be appreciated.
Many thanks
SergioIf you are running OAS 4.0.8.1 and Oracle 8.1.5 on the same machine then this could be the problem. These products are not certified to run on the same machine as they give a path conflict.
Hope this helps. -
PJC and database access through JDBC
Hello,
I'm trying to access to the database through a PJC via JDBC.
conn = DriverManager.getConnection ("jdbc:oracle:thin:@machine:1521:XE", "user", "pwd");It works fine on a XE database, but fails on another XE one:
Oracle JInitiator: Version 1.3.1.22
java.lang.NullPointerException
at oracle.jdbc.ttc7.O3log.marshal(O3log.java:606)
at oracle.jdbc.ttc7.TTC7Protocol.logon(TTC7Protocol.java:255)
at oracle.jdbc.driver.OracleConnection.<init>(OracleConnection.java:377)
at oracle.jdbc.driver.OracleDriver.getConnectionInstance(OracleDriver.java:515)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:345)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at oracle.forms.fd.AsyncJob.connect(AsyncJob.java:68)
at oracle.forms.fd.AsyncJob.run(AsyncJob.java:121)
at java.lang.Thread.run(Unknown Source)It also fails on a remote Unix database:
java.security.AccessControlException: access denied (java.net.SocketPermission monadev resolve)
at java.security.AccessControlContext.checkPermission(Unknown Source)
...so I edit the java.policy file of the Jinitiator directory:
permission java.net.SocketPermission "machine:port-", "accept,connect,listen,resolve"; and then get the same execption:
java.lang.NullPointerException
at oracle.jdbc.ttc7.O3log.marshal(O3log.java:606)
at oracle.jdbc.ttc7.TTC7Protocol.logon(TTC7Protocol.java:255)
...Finally, it work on only one machine and only a local database.
I'm probably missing something somewhere.
Is anyone could give me some light on this ?
Thanks in advance,
FrancoisI'm just learning to work with PJC's, so I'm unsure whether I can help, but here goes. I found the following archived on Google Groups (http://groups.google.com):
Hi. The basic applet security model is that it can only make connections
back to the machine from which it was downloaded. If you want to do
JDBC from an applet to a DBMS not on the applet-server machine,
you need a type-3 JDBC driver. A type-3 JDBC driver has an all-Java
client driver piece which an applet can download and use. This driver
piece connects to a proxy piece which is running on the webserver
machine. This proxy piece then connects to any DBMS anywhere on the
net, and is the middleman between the JDBC client and DBMS.
For security, management and performance reasons it's usually better to
constrain JDBC to a middle tier such as in a servlet, and use HTML to and
from the client, rather than the space and time involved in downloading a
full general query engine (a JDBC driver) to a client which typically uses
.1% of the capability or classes of the JDBC driver.
Joe Weinstein at BEA HTH,
Eric Adamson
Lansing, Michigan -
Hi!
I need help. I'm working with OC4J 9.0.2.0.0a behind Apache. In my application a have to obtain data of DataBase and show it in a fdf. To do that i have done a class that obtains the data and a servlet that show it in a fdf using classes of Adobe. The Adobe jar's name is jFdfTk. The servlet runs ok at port 7777, but when i change to port 80 the fdf doesn't show data. I can't understand why.
Does anyone have the same problem??
Can anyone help me??
Does anyone know why??
Thanks!I see now that I can use the old method of JNDI
lookup with the 3rd party messaging from a web
container, I just can't use the java:comp/resource/MQSeries logical JNDI location.
document: oracle 9ias Container for J2EE,
Services Guide
Release 2(9.0.3)
Aug 2002
Part No A97690-01
Chapter 9 Page 9-2
I am having trouble with this statement;
The ResourceProvider interface enables you to plug in
third-party message
providers for JMS connections. For Oracle JMS, this
allows EJBs, servlets, and OC4J
clients to access many different queue
implementations.
(OK good so far,)
With third-party message
providers, only EJBS can access queue
implementations. The resources are available
under java:comp/resource/ as the default JMS
resources.
WHAT? I can't do asynchronous messaging from a web
App to a MDB with a 3rd party JMS implementation?
What gives?
Can someone tell me this is not true please
Maybe you are looking for
-
Change R/3-XI in R/3-XI-XI
Hi, we have a scenario R/3-XI and we want to change this scenario to R/3-XI-XI. In our old szenario we have only configured a IDoc-Receiver with rfc-destination and port. We do not have a IDoc-Sender because we use the IDoc as Interface in the receiv
-
Mail stops working after 10.9.3 upgrade
Hello - After the 10.9.3 upgrade, Mail stopped retrieving new messages from my IMAP server. I can send e-mail from Mail without problem. I installed Airmail and it seems to work fine and I can also see the new e-mails by logging into the server via a
-
Libraries and playlists disappeared
Excuse me in advance for my poor English Today I opened iTunes as I usually do, and I couldn't see anything about my songs in the library and my plalist. It's all disappearex except the only album that is in the iTunes folder (everything else is situ
-
What happend to SMS in Address Book, I sure miss it !! Please bring it back in 10.5.1, thanks.
-
I can not down my printer and I do not know what is wrong.
Can you download my printer for me