JSP DB Connection

I wanted to connect to an oracle database using JSP. I've successfully done this. However, it looks like I will now have 1 giant file (jsp) with the db connection code included in it, and I think this is messy. So... I'd like to have a separate Java file which allows me to connect to the database, then somehow use this in the JSP file? I imagine the Java file would be compiled only once and would sit on the server while being accessed via the JSP file.
Is this possible? If so, any tips?
Thanks.

A bean is the preferred way to do it.
However, a more simpler method is simply put all of your database connection stuff in a standalone object, compile that object into a class file, place the class file in the appropriate directory, and simply invoke it as needed.
For example...
I have a class db that was created in db.java, with a constructor, various methods, and so on.
I place db.class in the classes directory of my Servlet Engine.
In my jsp page, I do...
<%@ page import "db" %>
and eventually...
<%
db myDatabaseConnection = new db;
db.connect();
resultSet results = db.executeQuery( query );
db.close();
%>
I think there should be some examples in your reference book (or tutorial). Simply look up importing other classes into your application. Please don't use mine, as there are some minor flaws and potential for trouble, but it should be good enough to give you an idea of what you can do.

Similar Messages

  • Using JSP to connect to an Access Database

    I need help on using JSP to connect to an Access database.
    This is the code I currently have connecting to a mySQL DB. I need to change it to connect to an Access DB. The reason I am switching DB's is because mySQL is no longer going to be carried by my host.
    Here is the code:
    <html>
    <head>
    <basefont face="Arial">
    </head>
    <body>
    <%@ page language="java" import="java.sql.*" %>
    <%!
    // define variables
    String UId;
    String FName;
    String LName;
    // define database parameters
    String host="localhost";
    String user="us867";
    String pass="jsf84d";
    String db="db876";
    String conn;
    %>
    <table border="2" cellspacing="2" cellpadding="5">
    <tr>
    <td><b>Owner</b></td>
    <td><b>First name</b></td>
    <td><b>Last name</b></td>
    </tr>
    <%
    Class.forName("org.gjt.mm.mysql.Driver");
    // create connection string
    conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user + "&password=" +
    pass;
    // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(conn);
    // query statement
    Statement SQLStatement = Conn.createStatement();
    // generate query
    String Query = "SELECT uid, fname, lname FROM abook";
    // get result
    ResultSet SQLResult = SQLStatement.executeQuery(Query);
         while(SQLResult.next())
              UId = SQLResult.getString("uid");
              FName = SQLResult.getString("fname");
              LName = SQLResult.getString("lname");
              out.println("<tr><td>" + UId + "</td><td>" + FName + "</td><td>" + LName
    + "</td></tr>");
    // close connection
    SQLResult.close();
    SQLStatement.close();
    Conn.close();
    %>
    </table>
    </body>
    </html>
    Thank You,
    Josh

    <%@ page language="java"%>
    <html>
    <head>
    <title>
    First Bean
    </title>
    <%@ page import="java.sql.*" %>
    </head>
    <body>
    <p>
    <%!
    Connection con;
    Statement st;
    ResultSet rs;
    String userid;
    String password;
    %>
    <%!public void db(JspWriter out)
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:phani");
    catch(Exception e){}
    try{
    st=con.createStatement();
    rs=st.executeQuery("SELECT * FROM login");
    while(rs.next())
    userid=rs.getString("userid");
    password=rs.getString("password");
    out.println(userid);
    out.println("</br>");
    out.println(password);
         out.println("</br>");     
    }catch(Exception e){}
    try{
    con.close();
    }catch(Exception e){}
    %>
    <%db(out);%>
    </p>
    </body>
    </html>
    phani is dsn name
    login is table name
    Good luck
    phani

  • Help need to know about JSP-RMI connection

    Hi All...
    Can anyone send me any tutorial/link about JSP-RMI connection. I need to access a RMI server object from JSP page.Is it possible?
    Looking for your responds.....

    Hi ...
    I didn't get any reply from any one....
    Is it possible to make Java Server Pages and RMI work
    together -sure, jsp's can make requests to servlets which can then talk to remote objects, then a response can be sent back down to the jsp
    to invoke a method on a server object from a JSP? And
    if, does
    someone know of a good tutorial, article etc., on
    this matter?hmm, Google, JSP Tutorial, RMI Tutorial, etc.

  • Jsp jdbc connectivity problem.

    i'm getting the following error
    "HTTP Status 500-----
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: /create_user.jsp(2,4) Invalid directive
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:88)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:527)
    org.apache.jasper.compiler.Parser.parseElements(Parser.java:1568)
    org.apache.jasper.compiler.Parser.parse(Parser.java:132)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:212)
    org.apache.jasper.compiler.ParserController.parse(ParserController.java:101)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:156)"
    for the jsp file is :
    <%@ page import="java.sql.*" %>
    <%@ //page errorPage="exceptionHandler.jsp"%>
    <%
    String connectionURL = "jdbc:mysql://localhost:3306/decipher?user=localhost;password=passwd";
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;
    %>
    <html><body>
    <%
    String nr="nr";
    String a= request.getParameter("emp_id");
    String b= request.getParameter("name");
    String c= request.getParameter("department");
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    connection = DriverManager.getConnection(connectionURL, "root", "passwd");
    statement = connection.createStatement();
    statement.executeUpdate("use decipher");
    statement.executeUpdate("Insert into candidate_details values ('" +a+ "','" +b+ "','" +c+ "')");
    %>
    sucesssfully created New Account
    </body>
    </html>"

    bmahesh7feb wrote:
    org.apache.jasper.JasperException: /create_user.jsp(2,4) Invalid directiveAt line 2, character 4 of create_user.jsp there's an invalid directive. This is a plain code syntax error.
    <%@ //page errorPage="exceptionHandler.jsp"%>What are those slashes doing there? Do you think that those Java style comments outcomments the JSP line? It is JSP code, it is not Java code. Remove the whole line or use JSP comments.
    As for the remnant of your JSP code, there are a lot of flaws in there. First step to in the right direction would be to stop using scriptlets in JSP. Good luck.

  • JSP Mysql Connection Problem

    Hi Friend,
    I am facing some problem in connecting mysql with jsp .
    When I try and connect to mysql with the following connection string
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdhiraj?user=root&password=dh");
    Statement statement     = con.createStatement();
    I get an error :
    java.sql.SQLException: Communication link failure: Bad handshake
    I don't know what is wrong,
    as I had tested mysql using telnet and it connects and executes sql nicely.
    Waiting for ur reply,
    Dhiraj Agrawal
    mail to : [email protected]

    Hi,
    You need to make sure that , you have given correct database name, user id and password in the connection url. and also check the jdbc driver is loaded properly. If your mysql is running in the standard port, you need not give the port as 3306.
    Here is the example :
    import java.sql.*;
         Notice, do not import org.gjt.mm.mysql.*
    or you will have problems!
    public class XampleClass
    public static void main(String[] Args)
    try {      
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    catch (Exception e) {
    System.err.println("exception while loading
    driver.");
    e.printStackTrace();
    try {
    Connection C = DriverManager.getConnection(
    "jdbc:mysql://localhost/test?user=myuser&password=mypwddb");
    // Do something with the Connection
    catch (SQLException e) {
    System.out.println("Exception: " + e);
    This is the format for conenction url :
    jdbc:mysql://[hostname][:port]/dbname[?param1=value1][&param2=value2]...
    Hope this helps you.
    Thanks,
    Senthil_Slash

  • Jsp-database connectivity problem

    hi
    There is a problem, when ever i write a jdbc code for database connectivity through MsAcess, in general applications it works fine. But when ever i try to the same using Jsps it throws an exception that " Microsoft jdbc-odbc driver not fount, Default driver not specified"
    please do help regarding this
    the code i used is
    package Products; import java.sql.*;import java.util.*; public class product{          public Vector getCategories()     {          Connection con;          Statement st;          ResultSet rs;          Vector ret=new Vector(1,1);          try          {               Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");               con=DriverManager.getConnection("jdbc:odbc:Web");               st=con.createStatement();               rs=st.executeQuery("Select * from Categories");               while(rs.next())               {                         ret.add(rs.getString(2));                    );               }          }          catch(Exception e)          {               //System.out.println("Exception...");               ret.add(e.getMessage());          }          return ret;     }}

    Have you downloaded the driver and put it in your Web-Server?
    In tomcat you simply need to copy the file in:
    Tomcat 5.0\common\lib

  • Help on JSP-RMI connection

    Hi..
    can anyone provide me any tutorial/link which will help me in learning JSP and RMI connection. Like I need to acces RMI server object from JSP.

    Hi ...
    I didn't get any reply from any one....
    Is it possible to make Java Server Pages and RMI work together -
    to invoke a method on a server object from a JSP? And if, does
    someone know of a good tutorial, article etc., on this matter?
    waiting for ur reply!!!!

  • Create a Jsp to connect to a java app to a website

    Hi, HELP, I really need HELP! hello, I have a java application and Im wondering is it possible to be able to open it in a website?- how do you create a JSP file that connects a java application to a website?

    Here is sample JAVA code:
    import java.net.*;
    import java.io.*;
    public class URLReader
        public URLReader(String website)
            try
                URL url = new java.net.URL(website);
                URLConnection connection = url.openConnection();
                connection.connect();
                DataInputStream reader = new DataInputStream(connection.getInputStream());
                byte b[] = new byte[connection.getContentLength()];
                int longitud = reader.read(b);
                if(longitud > 0)
                    for(int i=0;i<b.length;i++)
                        System.out.print((char)b);
    }catch(Exception e)
    e.printStackTrace();
    public static void main(String args[])
    if(args.length == 0)
                   System.out.println("Usage: URLReader URL");
              else
         URLReader uRLReader = new URLReader(args[0]);

  • JSP db connect doesnt work when deployed

    I have a VERY simple JSP selects from a table, displays the rows. Works fine when running in the local OC4J, but when i deploy it to the application server get the following. Any ideas?? I can post the JSP and web.xml and data-sources.xml if it would help..
    Thanks
    Robert
    500 Internal Server Error
    javax.servlet.jsp.JspException: SELECT buno, tec, org_code from acft: Io exception: The Network Adapter could not establish the connection     at org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doEndTag(QueryTagSupport.java:252)     at untitled1.jspService(_untitled1.java:69)     [SRC:/untitled1.jsp:15]     at com.orionserver[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].http.OrionHttpJspPage.service(OrionHttpJspPage.java:56)     at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:347)     at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:509)     at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:413)     at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)     at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:765)     at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:317)     at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:790)     at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.AJPRequestHandler.run(AJPRequestHandler.java:208)     at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].server.http.AJPRequestHandler.run(AJPRequestHandler.java:125)     at com.evermind[Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)     at java.lang.Thread.run(Thread.java:534)

    Deepak,
    I changed my web.xml file in jDeveloper to look like what you suggested, and removed the following
    <resource-env-ref>
    <resource-env-ref-name>jdbc/jacksonrsDS</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
    </resource-env-ref>
    I redeployed the application, and it still does not work.
    on another note, I did a search on the application server for datasources.xml and found 8 occurances of it. Is this normal, and which one is it looking at? is there a search order? I looked at them, and some had my jacksonrsDS defined in them, and others had my datasources from jDeveloper in the format of "jdev-connection-datasourcename"
    here is where i found them
    /home/oracle/product/10g/inf/j2ee/home/config
    /home/oracle/product/10g/inf/j2ee/OC4J_SECURITY/config
    /home/oracle/product/10g/mid/j2ee/home/config
    /home/oracle/product/10g/mid/j2ee/oc4j_portal/config
    /home/oracle/product/10g/mid/j2ee/MyOC4J/application_deployments/webapp1jspconnect
    /home/oracle/product/10g/mid/j2ee/MyOC4J/applications/webapp1jspconnect/META-INF
    /home/oracle/product/10g/mid/j2ee/MyOC4J/applications/webapp1jspconnect/webapp1jspconnect/WEB-INF/classes
    /home/oracle/product/10g/mid/j2ee/MyOC4J/config

  • JSP Exception: connection reset by peer

    ervlet.jsp.JspException: Can't write string 'Asset Library' : Connection reset by peer.
    at org.apache.struts.taglib.tiles.InsertTag$DirectStringHandler.doEndTag()I(InsertTag.java:1026)
    at org.apache.struts.taglib.tiles.InsertTag.doEndTag()I(InsertTag.java:473)
    at jsp_servlet._pages._common._layouts.__mainlayout._jspService(Ljavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)V(__mainlayout.java:325)
    at weblogic.servlet.jsp.JspBase.service(Ljavax.servlet.ServletRequest;Ljavax.servlet.ServletResponse;)V(JspBase.java:33)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run()Ljava.lang.Object;(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax.servlet.ServletRequest;Ljavax.servlet.ServletResponse;Lweblogic.servlet.internal.FilterChainImpl;)V(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax.servlet.ServletRequest;Ljavax.servlet.ServletResponse;)V(ServletStubImpl.java:315)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(Ljavax.servlet.ServletRequest;Ljavax.servlet.ServletResponse;)V(RequestDispatcherImpl.java:322)
    at org.apache.struts.action.RequestProcessor.doForward(Ljava.lang.String;Ljavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)V(RequestProcessor.java:1069)
    at org.apache.struts.tiles.TilesRequestProcessor.doForward(Ljava.lang.String;Ljavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)V(TilesRequestProcessor.java:274)
    at org.apache.struts.tiles.TilesRequestProcessor.processTilesDefinition(Ljava.lang.String;ZLjavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)Z(TilesRequestProcessor.java:2
    at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(Ljavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;Lorg.apache.struts.config.ForwardConfig;)V(TilesRequ
    at org.apache.struts.action.RequestProcessor.process(Ljavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)V(RequestProcessor.java:279)
    at org.apache.struts.action.ActionServlet.process(Ljavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)V(ActionServlet.java:1482)
    at org.apache.struts.action.ActionServlet.doGet(Ljavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)V(ActionServlet.java:507)
    at javax.servlet.http.HttpServlet.service(Ljavax.servlet.http.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)V(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(Ljavax.servlet.ServletRequest;Ljavax.servlet.ServletResponse;)V(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run()Ljava.lang.Object;(ServletStubImpl.java:1006)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax.servlet.ServletRequest;Ljavax.servlet.ServletResponse;Lweblogic.servlet.internal.FilterChainImpl;)V(ServletStubImpl.java:419)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax.servlet.ServletRequest;Ljavax.servlet.ServletResponse;)V(ServletStubImpl.java:315)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run()Ljava.lang.Object;(WebAppServletContext.java:6718)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(Lweblogic.security.subject.AbstractSubject;Ljava.security.PrivilegedAction;)Ljava.lang.Object;(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(Lweblogic.security.acl.internal.AuthenticatedSubject;Lweblogic.security.acl.internal.AuthenticatedSubject;Ljava.security.PrivilegedAction;)Ljava.lang.
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(Lweblogic.servlet.internal.ServletRequestImpl;Lweblogic.servlet.internal.ServletResponseImpl;)V(WebAppServletContext.java:3764)
    at weblogic.servlet.internal.ServletRequestImpl.execute(Lweblogic.kernel.ExecuteThread;)V(ServletRequestImpl.java:2644)
    at weblogic.kernel.ExecuteThread.execute(Lweblogic.kernel.ExecuteRequest;)V(ExecuteThread.java:219)
    at weblogic.kernel.ExecuteThread.run()V(ExecuteThread.java:178)
    at java.lang.Thread.startThreadFromVM(Ljava.lang.Thread;)V(Unknown Source)
    When I find the data it's giving result alon with the above exception.
    Can any one help?

    maybe put in abit of effort and tell the forum what you are trying and what is casuing this error, furthermore put in a little bit more effort and read the text behind the Formatting Tips url provided above the textarea you used to paste your stacktrace in.

  • Using jsp to connect SavingAccount tutorial example

    Hello
    I have a question on the tutorial i do not know if this is the right place but here it is
    I tried to change the SavingAccount EJB (j2eettutorial exmple chapter 24)and add a Web client to it. I modified the JSP which was used in the converter exmple to use savingsAccount Ejbs.
    I have spent a week on this simple example, it compiles, and deployed without a problem but when i run it on the browser it says error 404 the page does not exist.
    the exmple is only one Bean with two interfaces and one jsp page called index.jsp I am going mad, started to panic there is nothing wrong still why it does not work.
    I packaged the bean and used /context root for jsp imported the bean in jsp give the resource ref inside the jsp ...
    I do not understand what is the mestray behind this. is it because i only use one simple jsp? than what else should use to connect to ejb? can anyone help me please

    the code for Ejb bean classe
    package bookings;
    import java.sql.*;
    import javax.sql.*;
    import java.util.*;
    import java.util.Date;
    import java.math.*;
    import javax.ejb.*;
    import javax.naming.*;
    public class BookBean implements EntityBean {
        private final static String dbName = "java:comp/env/jdbc/BooksDB";
        private String ISBN;
        private String title;
        private String author;
        private String borrowedBy;
        private String dateDue;
        private EntityContext context;
        private Connection con;
         public String getISBN() {
            return ISBN;
        public String getTitle() {
            return title;
        public String getAuthor() {
            return author;
        public String getBorrowedBy() {
            return borrowedBy;
    public String getDateDue() {
            return dateDue;
        public String ejbCreate(String ISBN, String title, String author,
            String borrowedBy, String dateDue) throws CreateException {
            try {
                insertRow(ISBN, title, author, borrowedBy, dateDue);
            } catch (Exception ex) {
                throw new EJBException("ejbCreate: " + ex.getMessage());
            this.ISBN = ISBN;
            this.title = title;
            this.author = author;
            this.borrowedBy = borrowedBy;   
            this.dateDue = dateDue;
            return ISBN;
        public String ejbFindByPrimaryKey(String primaryKey)
            throws FinderException {
            boolean result;
            try {
                result = selectByPrimaryKey(primaryKey);
            } catch (Exception ex) {
                throw new EJBException("ejbFindByPrimaryKey: " + ex.getMessage());
            if (result) {
                return primaryKey;
            } else {
                throw new ObjectNotFoundException("Row for      ISBN " + primaryKey +
                    " not found.");
        public Collection ejbFindByTitle(String title)
            throws FinderException {
            Collection result;
            try {
                result = selectByTitle(title);
            } catch (Exception ex) {
                throw new EJBException("ejbFindByTitle " + ex.getMessage());
            return result;
        public Collection ejbFindByAuthor(String author)
            throws FinderException {
            Collection result;
            try {
                result = selectByAuthor(author);
            } catch (Exception ex) {
                throw new EJBException("ejbFindByAuthor: " + ex.getMessage());
            return result;
        public void ejbRemove() {
            try {
                deleteRow(ISBN);
            } catch (Exception ex) {
                throw new EJBException("ejbRemove: " + ex.getMessage());
        public void setEntityContext(EntityContext context) {
            this.context = context;
        public void unsetEntityContext() {
        public void ejbActivate() {
            ISBN = (String) context.getPrimaryKey();
        public void ejbPassivate() {
            ISBN = null;
        public void ejbLoad() {
            try {
                loadRow();
            } catch (Exception ex) {
                throw new EJBException("ejbLoad: " + ex.getMessage());
        public void ejbStore() {
            try {
                storeRow();
            } catch (Exception ex) {
                throw new EJBException("ejbStore: " + ex.getMessage());
        public void ejbPostCreate(String ISBN, String title, String author,
            String borrowedBy,String dateDue) {
        /*********************** Database Routines *************************/
        private void makeConnection() {
            try {
                InitialContext ic = new InitialContext();
                DataSource ds = (DataSource) ic.lookup(dbName);
                con = ds.getConnection();
            } catch (Exception ex) {
                throw new EJBException("Unable to connect to database. " +
                    ex.getMessage());
        private void releaseConnection() {
            try {
                con.close();
            } catch (SQLException ex) {
                throw new EJBException("releaseConnection: " + ex.getMessage());
        private void insertRow(String ISBN, String title, String author,
            String borrowedBy, String dateDue) throws SQLException {
            makeConnection();
            String insertStatement =
                "insert into books values ( ? , ? , ? , ? )";
            PreparedStatement prepStmt = con.prepareStatement(insertStatement);
            prepStmt.setString(1, ISBN);
            prepStmt.setString(2, title);
            prepStmt.setString(3, author);
            prepStmt.setString(4, borrowedBy);
             prepStmt.setString(5, dateDue);
            prepStmt.executeUpdate();
            prepStmt.close();
            releaseConnection();
        private void deleteRow(String ISBN) throws SQLException {
            makeConnection();
            String deleteStatement = "delete from Books where ISBN = ? ";
            PreparedStatement prepStmt = con.prepareStatement(deleteStatement);
            prepStmt.setString(1, ISBN);
            prepStmt.executeUpdate();
            prepStmt.close();
            releaseConnection();
        private boolean selectByPrimaryKey(String primaryKey)
            throws SQLException {
            makeConnection();
            String selectStatement =
                "select ISBN " + "from Books where ISBN = ? ";
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, primaryKey);
            ResultSet rs = prepStmt.executeQuery();
            boolean result = rs.next();
            prepStmt.close();
            releaseConnection();
            return result;
        private Collection selectByTitle(String title)
            throws SQLException {
            makeConnection();
            String selectStatement =
                "select ISBN" + "from bo where title = ? ";
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, title);
            ResultSet rs = prepStmt.executeQuery();
            ArrayList a = new ArrayList();
            while (rs.next()) {
                String ISBN = rs.getString(1);
                a.add(ISBN);
            prepStmt.close();
            releaseConnection();
            return a;
        private Collection selectByAuthor(String author)
            throws SQLException {
            makeConnection();
            String selectStatement =
                "select ISBN from Books " +
                "where author = ?";
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, author);
            ResultSet rs = prepStmt.executeQuery();
            ArrayList a = new ArrayList();
            while (rs.next()) {
                String ISBN = rs.getString(1);
                a.add(ISBN);
            prepStmt.close();
            releaseConnection();
            return a;
        private void loadRow() throws SQLException {
            makeConnection();
            String selectStatement =
                "select title, author,borrowedBy, dateDue " +
                "from Books where ISBN = ? ";
            PreparedStatement prepStmt = con.prepareStatement(selectStatement);
            prepStmt.setString(1, this.ISBN);
            ResultSet rs = prepStmt.executeQuery();
            if (rs.next()) {
                this.title = rs.getString(1);
                this.author = rs.getString(2);
                this.borrowedBy=rs.getString(3);
                this.dateDue = rs.getString(4);
                prepStmt.close();
            } else {
                prepStmt.close();
                throw new NoSuchEntityException("Row for ISBN " + ISBN +
                    " not found in database.");
            releaseConnection();
        private void storeRow() throws SQLException {
            makeConnection();
            String updateStatement =
                "update Books set title =  ? ," +
                "author = ? , borrowedBy = ? " + " dateDue = ?, where ISBN = ?";
            PreparedStatement prepStmt = con.prepareStatement(updateStatement);
            prepStmt.setString(1, title);
            prepStmt.setString(2, author);
            prepStmt.setString(3, borrowedBy);       
            prepStmt.setString(4, dateDue);
            prepStmt.setString(5, ISBN);
            int rowCount = prepStmt.executeUpdate();
            prepStmt.close();
            if (rowCount == 0) {
                throw new EJBException("Storing row for ISBN " + ISBN + " failed.");
            releaseConnection();
    // end of BookBean the code for remot interface
    package bookings;
    import java.rmi.RemoteException;
    // Java extension packages
    import javax.ejb.*;
    public interface Book extends EJBObject {
        public void getISBN() throws RemoteException;
        public String getTitle() throws RemoteException;
        public String getAuthor() throws RemoteException;
        public String getBorrowedBy() throws RemoteException;
        public String getDateDue() throws RemoteException;
    }the codes for home // BookHome.java
    // BookHome is the home interface for entity EJB Book.
    package bookings;
    import java.util.Collection;
    import java.rmi.RemoteException;
    // Java extension packages
    import javax.ejb.*;
    public interface BookHome extends EJBHome {
        // create Book EJB using given book details
       public Book create( String ISBN, String title, String author,
            String borrowedBy, String dateDue)  throws RemoteException, CreateException;
       // find Book with given ISBN
       public Book findByPrimaryKey( String isbn )
          throws RemoteException, FinderException;
       // find all Books
       public Collection findAllBooks()
          throws RemoteException, FinderException;
       // find Books with given title
       public Collection findByTitle( String title )
          throws RemoteException, FinderException;
         // find Books with given author
        public Collection findByAuthor(String author)
            throws FinderException, RemoteException;
      // find Books with given author
        public Collection findBorrowedBy(String borrowedBy)
            throws FinderException, RemoteException;
      }the code for index.jsp to use the ejb which i get this error messgae when i run it
    HTTP 404 - File not found
    Internet Explorer i can tell you that i have deployed 8 times with changes
    <%@ page import="bookings.*, javax.ejb.*, javax.naming.*, javax.rmi.PortableRemoteObject, java.rmi.RemoteException" %>
    <%!
       private Book book = null;
       public void jspInit() {
          try {
             InitialContext ic = new InitialContext();
             Object objRef = ic.lookup("java:comp/env/ejb/TheBooking");
             BookHome home = (BookHome)PortableRemoteObject.narrow(objRef, BookHome.class);
             book = home.create();
          } catch (RemoteException ex) {
                System.out.println("Couldn't create book bean."+ ex.getMessage());
          } catch (CreateException ex) {
                System.out.println("Couldn't create book bean."+ ex.getMessage());
          } catch (NamingException ex) {
                System.out.println("Unable to lookup home: "+ "TheBook "+ ex.getMessage());
       public void jspDestroy() {   
             book = null;
    %>
    <html>
    <head>
        <title>Book</title>
    </head>
    <body bgcolor="white">
    <h1><b><center>Book</center></b></h1>
    <hr>
    <p>Enter an ISBN:</p>
    <form method="get">
    <input type="text" name="amount" size="25">
    <br>
    <p>
    <input type="submit" value="Submit">
    <input type="reset" value="Reset">
    </form>
    <%
        String isbn = request.getParameter("isbn");
    %>
       <p>
       <%= isbn %> the book isbn is  <%= book.getISBN() %> 
       <p>
       <%= title %> the book title <%= book.getTitle() %> 
    </body>
    </html>

  • JSP Timoeut connection problem

    I'm developing a little demo Search Engine program using JSP and Tomcat4.1.18. After I launch the query my program calculates the results, and it may take a few minutes. But after a bit Tomcat gives me the message "timeout connection", while my application is still calculating. How can I set the Jsp in order to keep the server in waiting?
    Thanks
    David

    In the web.xml configuration file of your tomcat you can set the session timeout time.

  • Why JApplet and JSP cannot connect to MySQL

    When i use applet connect to MySQL, it show that no suitable driver.
    My program is
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    public class fuck extends JApplet implements ActionListener
    private JButton bb = new JButton("update");
    private JTextArea aa = new JTextArea(1,7);
    private JTextArea ss = new JTextArea(1,7);
    private JPanel pp = new JPanel();
    public fuck()
    Container c=getContentPane();
    pp.add(aa);
    pp.add(ss);
    pp.add(bb);
    c.add(pp);
    bb.addActionListener(this);
    public void actionPerformed(ActionEvent ee)
    try
    Class.forName("org.gjt.mm.mysql.Driver");
    catch(ClassNotFoundException e)
    System.out.println(e.getMessage());
    try
    Connection con =
    DriverManager.getConnection("jdbc:mysql://localhost/air","root","");
    Statement st = con.createStatement();
    //PreparedStatement pst = con.prepareStatement(
    // "update aa set condition=? where temp=?");
    //pst.setInt(1,3);
    //pst.setString(2,"hg");
    //pst.executeUpdate();
    ResultSet rs=
    st.executeQuery("select * from aa");
    while (rs.next())
    aa.setText(rs.getString("temp"));
    ss.setText(rs.getString("condition"));
    st.close();
    con.close();
    catch(SQLException ex)
    System.err.println("SQLException:"+ex.getMessage());
    If I using JSP, it also have some condition

    Clearly it is in the classpath, otherwise the error would have been "Class not found". But here's a quote from the documentation for the driver, the part that explains how to make a connection:// The newInstance() call is a work around for some
    // broken Java implementations
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();The "broken Java implementations" it refers to are certain JVMs that run applets in browsers...

  • [b]Config JDBC for JSP to connect to OracleDB[/b]

    I use iWS6.0 and JDK1.2 to enable JSP.
    To use JDBC Driver to connect to OracleDB, I simply set CLASSPATH to the location of classes12.zip, and I have tested in java command-line, it worked fine.
    To let JSP work with JDBC, I edit file jvm12.conf so that the jvm.classpath to location of classes12.zip, but it doesn't work.
    Could someone guide me to the solution, or some document to read.

    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");Modify these lines as this, checking whtr the driver is available in the correspopnding package...
    Class.forName("COM.ibm.db2.jdbc.net.DB2Driver");
    i suppose that this works out well.

  • Oracle Single Sign on JSP Database Connection

    I am writing a JSP Search Screen that launches off of Oracle Portal (behind SSO). What I'm looking to do is have the JSP connect to the database as that user, and then show the information available to that user (we have this handled by a VPD). I was wondering how I could get access to the single signon RAD in order to connect to the database from within my JSP. Any help would be greatly appreciated.

    Hi Darsh,
    1. Oracle Internet Directory (OID) is Oracle LDAP storage solution (more here), Oracle Virtual Directory is Oracle solution that can read identity data (and filter it (mask it) based on policies) from Oracle/non-Oracle databases, Oracle/non-Oracle Directories and files and provide the user profiles as LDAP view (more here), There is nothing called Oracle Active Directory, you must be referring to Microsoft Active Directory.
    2. No, Oracle Single Sign On (OSSO) is a feature in iAS (its obsolete), Identity Management is wide umbrella of solutions and concepts.
    3. Oracle Access Manager is one component of Oracle Identity and Access Management suite of products.
    4. Webgate is Oracle access Manager agent that is installed on a webtier, it intercepts the web requests and collect the credentails, send them to Oracle Access Manager for security evaluation (decide what Authentication is needed, verify collect credentials, etc), webgate then enforce the Access Manager decision.
    5. Oracle EBS AccessGate is a java application that has the same use of OAM Webgate (it is OAM agent) but specific to E Business suite, EBS Access Gate is the new solution replacing OSSO agents, OAM is replacing OSSO server component, EBS and OSSO customers can use OAM server with OSSO agents, or with EBS AccessGate.
    HTH.
    Ghassan

Maybe you are looking for