JDBC thru Servlets

Hi there,
I have a HTML form, which will submit some details to a servlet. In that Servlet i am connecting to a Database(thru JDBC) to insert those form details. I was writing my code in doPost() method of my Servlet. I used to Open the DB connection and close it when come out of the servlet(i used to redirect to a JSP thru RequestDispatcher Object). Theform will be used by many clinets, so there is lot of DB connection opening and closing going to happen.
But recently i came to know instead of writing DB opening and closing code in doPost(), we can write it in init(), so that only one connection will be made and it can be used for all the threads of the servlets.
My doubt,
If it is so, where should i write my DB connection close method()?
Does anybody have a sample code of this, ?.
Thanx in advance
javaIdiot

If you write the connection establishment code in the init() the close should go in the destroy() method.
This way there will be one connection per servlet instance instead of connection per request. But at a given time there might be multiple connection becouse there can be multiple servlet instances in memory.
The best solution would be using a connection pool and take a connection from the pool when you need and release it when you dont need it.
Take a look at the apache-commons-dbcp project
http://jakarta.apache.org/commons/dbcp/

Similar Messages

  • Servlets/JDBC vs. servlets/EJB performance comparison/benchmark

    I have a PHB who believes that EJB has no ___performance___ benefit
    against straightforward servlets/JSP/JDBC. Personally, I believe that
    using EJB is more scalable instead of using servlets/JDBC with
    connection pooling.
    However, I am at a lost on how to prove it. There is all the theory, but
    I would appreciate it if anyone has benchmarks or comparison of
    servlets/JSP/JDBC and servlets/JSP/EJB performance, assuming that they
    were tasked to do the same thing ( e.g. performance the same SQL
    statement, on the same set of tables, etc. ).
    Or some guide on how to setup such a benchmark and prove it internally.
    In other words, the PHB needs numbers, showing performance and
    scalability. In particular, I would like this to be in WLS 6.0.
    Any help appreciated.

    First off, whether you use servlets + JDBC or servlets + EJB, you'll
    most likely spend much of your time in the database.
    I would strongly suggest that you avoid the servlets + JDBC
    architecture. If you want to do straight JDBC code, then it's
    preferable to use a stateless session EJB between the presentation layer
    and the persistence layer.
    So, you should definitely consider an architecture where you have:
    servlets/jsp --> stateless session ejb --> JDBC code
    Your servlet / jsp layer handles presentation.
    The stateless session EJB layer abstracts the persistence layer and
    handles transaction demarcation.
    Modularity is important here. There's no reason that your presentation
    layer should be concerned with your persistence logic. Your application
    might be re-used or later enhanced with an Entity EJB, or JCA Connector,
    or a JMS queue providing the persistence layer.
    Also, you will usually have web or graphic designers who are modifying
    the web pages. Generally, they should not be exposed to transactions
    and jdbc code.
    We optimize the RMI calls so they are just local method calls. The
    stateless session ejb instances are pooled. You won't see much if any
    performance overhead.
    -- Rob
    jms wrote:
    >
    I have a PHB who believes that EJB has no ___performance___ benefit
    against straightforward servlets/JSP/JDBC. Personally, I believe that
    using EJB is more scalable instead of using servlets/JDBC with
    connection pooling.
    However, I am at a lost on how to prove it. There is all the theory, but
    I would appreciate it if anyone has benchmarks or comparison of
    servlets/JSP/JDBC and servlets/JSP/EJB performance, assuming that they
    were tasked to do the same thing ( e.g. performance the same SQL
    statement, on the same set of tables, etc. ).
    Or some guide on how to setup such a benchmark and prove it internally.
    In other words, the PHB needs numbers, showing performance and
    scalability. In particular, I would like this to be in WLS 6.0.
    Any help appreciated.--
    Coming Soon: Building J2EE Applications & BEA WebLogic Server
    by Michael Girdley, Rob Woollen, and Sandra Emerson
    http://learnweblogic.com

  • Which tutorials may you suggest for JDBC and servlets?

    Hello, i would to learn about JDBC and servlets.
    May you please suggest me a good tutorial(e.g.post me a link) in order to study for JDBC and servlets?
    e.g. How to make a servlet etc.
    Thanks, in advance!

    I agree with PhHein, it's best to learn one technology and then the other. (Just my two cents, but start with JDBC from a simple standalone application, then when that is working, try to tackle Servlets, since you will need to also learn how to get them working in a container like Tomcat).
    Here is a tutorial that has both concepts in it at the same time. Site is down now, but is usually up. http://www.roseindia.net/jdbc/jdbcconnectivity.shtml
    Also, you will eventually want to download a J2EE container such as Tomcat or Jboss.
    - Saish

  • JDBC on Servlets

    The following worked on my machine as a java console, but tomcat does not seem to like ir. It excepts on classnotfound
    com.mysql.jdbc.Driver
    help?
    try
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    catch (Exception e)
    System.out.println(e.toString());
    // localhost192.168.1.101
    Connection conn =
    DriverManager.getConnection("jdbc:mysql://localhost:3306?" +
    "user=root&password=secret");

    JDBC on Servlets ...is undesirable for most (professional) projects.
    try to keep db access code out of your web app if
    possible. It's just good conventionAt best that statement is confusing.
    I can only guess that you were suggesting that a database layer should be used rather than putting the JDBC code directly in the servlet code.

  • JDBC using Servlets!!!!!!Hurry up!

    Hi,
    MySelf Savdeep Vasudeva,Presently I am involved in a project using JDBC-ODBC Bridge in which I want to connect a database table to a HTML Page using Java Servlets.When I fill the form on the HTML Page using numeric data in all my variables,it works quite good and the query is executed.Consequently the data of the person who has filled in the form is displayed.But when I want to change one of the numeric variables(parameter variable) to a String by also making the data type change in my table from numeric to character.The query is not executed at all and It gives the exception message.Kindly help me that how should I make a query in the Java Servlets using the String Variables in the condition.Presently I am only Limited to numeric
    variables.Waiting for a quick response from your side.
    Regards,
    Savdeep Vasudeva.
    E-mail: [email protected]

    Savdeep,
    it would really help, if u posted some part of the erroneous code. anyway, u say u have changed the datatype in ur table to string, but while receiving the parameters, what ru using?
    for integers values u would have been using something like: rs.getInt(col index);
    whereas to get a string value u have to use:
    rs.getString(col index);
    are u making this change in ur code???
    keep progRamming...
    -satyen

  • Open new browser window thru servlet

    From the parent browser window I would like to open new window on top of parent. How do I do this in a servlet? Thanks so much.

    Actually, I'm already doing this in my servlet. I'm using JavaScript to write out the window but it isn't letting me do everything I need to do. I would really like to figure out a way to write out the window thru Java Servlet code, but if that isn't possible I'll have to go another route.
    Thanks.

  • Java script problem in JSP called thru servlet

    when jsp page is displayed thru a servlet in following way the java scripts built in that JSP page are not working.
    ServletContext sc = getServletContext();
         RequestDispatcher rd = sc.getRequestDispatcher(url);
         rd.include(req, res);
    how can i enable these java scripts?

    Most probably you have something like this:
    <script language="JavaScript1.2" src="menu.js"></script>
    The bit that is probably causing the problem is the src attribute.
    Its a common issue when using the request dispatcher
    You request "/servlets/myServlet"
    it forwards to "/jsp/myJSP"
    You try and access a resource using a relative URL.
    however, the browser knows nothing about the forward being done - it thinks that the URL is /servlets/myServlet, when you want it to be /jsp/myJSP.jsp
    So if you access menu.js it will look in /servlets/menu.js instead of /jsp/menu.js (example only)
    to fix
    1 - Don't use relative links. Ie use /scripts/menu.js to import the script
    2 - use a <base> tag <base href="http://www.mywebsite.com/jsp/> This tells a web page where to resolve relative references from.
    Hope this helps,
    evnafets

  • Connection to the Database thru Servlet

    Hello:
    I have just read some threads in this forum and noticed that people saying that connecting to the database in JSP is not a good Java Programming Habit. So, could you please give a little guidance on connection to the Oracle database in servlet. Thank you very much.
    Oscar.

    You use standard JDBC:
    http://java.sun.com/docs/books/tutorial/jdbc/index.htmlIn a servlet container, most of the time, you set up a connection pool that you access through JNDI
    http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.htmlFor larger applications you might want to use "Data Access Objects"
    http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.htmlCheers,
    evnafets

  • JDBC and Servlets

    I am writing a servlet which retrieves data from a database into a result set. I want to compare a username (taken into the servlet via a form for example) with a username from the result set.
    Can anyone tell me how this might be coded? Thanx.

    get the userid and password from the html form:
    String userid = req.getParameter("userid").trim();
    String password = req.getParameter("password").trim();
    find userid and password from database:
    String sql="SELECT PASSWORD FROM USER WHERE USERID =?";
    try{
    Class.forName(".............");
    con = DriverManager.getConnection(url,user,password);
    pstmt = con.prepareStatement(sql);
    pstmt.setString(1,userid);
    ResultSet result = pstmt.executeQuery();
    if(result != null){
    result.next();
    String pwd_DB = result.getString(1);
    Compare password:
    if (pwd_DB.equals(password)
    Hope it will give you some help.
    Yen

  • Configuring Exception pages thru servlets for tomcat5

    Hi,
    I am trying to configure exception pages for servlets. But cannot get it done. I have one servlet ServletMapping.java. I am defining in web.xml, that any error should go to the servlet ErrorDisplay.java, which in turn handles the error. I have written for javax.servlet.ServletException.
    But the control does not go to the error page servlet ErrorDisplay.java
    thanx in advance
    -biyat
    Here is my web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
    <web-app>
    <display-name>Biyat Testing System for web development</display-name>
    <description>
    Used to write Jsp/ Servlets
    </description>
    <servlet>
    <servlet-name>ServletMapping</servlet-name>
    <servlet-class>code.ServletMapping</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ServletMapping</servlet-name>
    <url-pattern>/code/ServletMapping</url-pattern>
    </servlet-mapping>
    <servlet>
    <servlet-name>ErrorDisplay</servlet-name>
    <servlet-class>code.ErrorDisplay</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ErrorDisplay</servlet-name>
    <url-pattern>/code/ErrorDisplay</url-pattern>
    </servlet-mapping>
    <error-page>
    <exception-type>javax.servlet.ServletException</exception-type>
    <location>/code/ErrorDisplay</location>
    </error-page>
    </web-app>
    Here is my servlets
    in webexp/WEB-INF/classes
    code/ErrorDisplay.java
    package code;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ErrorDisplay extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String code=null, message=null, type=null;
    Object codeObj, messageObj, typeObj;
    codeObj = request.getAttribute("javax.servlet.error.status_code");
    messageObj = request.getAttribute("javax.servlet.error.message");
    typeObj = request.getAttribute("javax.servlet.error.exception_type");
    if(codeObj != null)
    code = codeObj.toString();
    if(messageObj!=null)
    message = messageObj.toString();
    if(typeObj != null)
    type = typeObj.toString();
    String reason = (code!=null ? code : type);
    out.println("<html>");
    out.println("<head><title>"+reason+":- "+message+"</title></head>");
    out.println("<body>");
    out.println("<h1>"+reason+"</h1>");
    out.println("<h1>"+message+"</h1>");
    out.println("<hr>");
    out.println("<i>Error accessing "+request.getRequestURI()+"</i>");
    out.println("</body></html>");
    Here is the page where there is error.
    in webexp/WEB-INF/classes
    code/ServletMapping.java
    package code;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ServletMapping extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    String var1 = "logging starts";
    String str = request.getParameter("hello");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    FileInputStream fis = new FileInputStream("hello.gif");
    out.println("<html><body><font color=red><b>Hello Biyat</b></font></body></html>");

    Hi, Biyat,
    The first thing I can see would help is to also define an error page for java.io.IOException - you can even re-use the same error page by adding the following to web.xml:
    <error-page>
    <exception-type>java.io.IOException</exception-type>
    <location>/code/ErrorDisplay</location>
    </error-page>
    djiao

  • Implementing  jdbc using jsp and servlets

    please give me documnetation and few programs with code .
    implementing or using jdbc with servlets and jsp.

    please give me documnetation and few programs with
    code .
    implementing or using jdbc with servlets and jsp.Well, which do you want to do? Implement JDBC with servlets and JSP - a tricky job, but there's no technical reason why you couldn't for instance write a class which both extends HttpServlet and implements java.sql.Driver. Wouldn't recommend it, though

  • Servlet with Jdbc

    Hello,
    Can someone tells me how can I combine Jdbc and servlets.
    If someone has an example it's very nice.
    Thanks in advance
    kamel
    null

    I think i can help you.The example is :
    import java.io.* ;
    import java.sql.* ;
    import javax.sql.*;
    import oracle.jdbc.driver.*;
    public class test extends HttpServlet
    public void init(ServletConfig conf) throws ServletException
    super.init(conf);
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    res.setContentType("text/html;charset=GB2312");
    ServletOutputStream out=res.getOutputStream();
    out.println("test");
    try
    Class.forName ("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection
    ("jdbc:oracle:oci8:@oraserver", "ycjx", "xjcy");
    // ("jdbc:oracle:oci8:@qit-uq-cbiw_orcl", "scott", "tiger");
    // or oci7 @TNSNames_Entry, userid, password
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery("select sj from dy_xstw");
    rset.next();
    out.println(rset.getString(1));
    rset.close();
    stmt.close();
    conn.close();
    catch (SQLException ex) {out.println("err1");}
    catch (ClassNotFoundException ex) { out.println("err2");}
    catch (java.lang.Exception ex) {out.println("err3"); }
    }

  • Servlet JDBC

    Can anyone please help me with pointing to the right direction on webapplications.
    I have a table in the database that returns 50K rows when running a query. I have been reading through some books and forums, SDN including that a correct way to access the database is through the Business tier EJB session beans and JPA and access these objects from Servlets. I understand that and I have an example that works using paging so I do not need to send all 50K records at once. My question is, the resultset retrieves entity objects and I have to create data transfer objects for each one of them to send to the GWT client? Doesn't it mean I have twice as much objects in the memory at a time to compare with accessing database through JDBC from Servlets directly? In the later case I wouldn't have any entity objects and occupy less memory? Is it completely wrong idea?
    Thanks

    mambo_jumbo wrote:
    Without their superpowers some of them are still not serializable for GWT.
    Never mind,
    Thanks for answer.I don't understand what the problem is here.
    Dod you have a problem with making them Serializable? They have to be Serializable if you want to make them arguments to remote methods anyway.

  • HELP! How te retrieve the last row in MYSQL database using Servlet!

    Hi ,
    I am new servlets. I am trying to retireve the last row id inserted using the servlet.
    Could someone show me a working sample code on how to retrieve the last record inserted?
    Thanks
    MY CODE
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class demo_gr extends HttpServlet {
    //***** Servlet access to data base
    public void doPost (HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException
         String url = "jdbc:mysql://sql2.njit.edu/ki3_proj";
              String param1 = req.getParameter("param1");
              PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");
              String semail, sfname, slname, rfname, rlname, remail, message;
              int cardType;
              sfname = req.getParameter("sfname");
              slname = req.getParameter("slname");
              rfname = req.getParameter("rfname");
              rlname = req.getParameter("rlname");
              semail = req.getParameter("semail");
              remail = req.getParameter("remail");
              message = req.getParameter("message");
              //cardType = req.getParameter("cardType");
              cardType = Integer.parseInt(req.getParameter("cardType"));
              out.println(" param1 " + param1 + "\n");
         String query = "SELECT * FROM greeting_db "
    + "WHERE id =" + param1 + "";
              String query2 ="INSERT INTO greeting_db (sfname, slname ,semail , rfname , rlname , remail , message , cardType ,sentdate ,vieweddate) values('";
              query2 = query2 + sfname +"','"+ slname + "','"+ semail + "','"+ rfname + "','"+ rlname + "','"+ remail + "','"+ message + "','"+ cardType + "',NOW(),NOW())";
              //out.println(" query2 " + query2 + "\n");
              if (semail.equals("") || sfname.equals("") ||
              slname.equals("") || rfname.equals("") ||
              rlname.equals("") || remail.equals("") ||
              message.equals(""))
                        out.println("<h3> Please Click the back button and fill in <b>all</b> fields</h3>");
                        out.close();
                        return;
              String title = "Your Card Has Been Sent";
              out.println("<BODY>\n" +
    "<H1 ALIGN=CENTER>" + title + "</H1>\n" );
                   out.println("\n" +
    "\n" +
    " From  " + sfname + ", " + slname + "\n <br> To  "
                                            + rfname + ", " + rlname + "\n <br>Receiver Email  " + remail + "\n<br> Your Message "
                                            + message + "\n<br> <br> :");
                   if (cardType ==1)
                        out.println("<IMG SRC=/WEB-INF/images/bentley.jpg>");
                   else if(cardType ==2) {
                        out.println("<IMG SRC=/WEB-INF/images/Bugatti.jpg>");
                   else if(cardType ==3) {
                        out.println(" <IMG SRC=/WEB-INF/images/castle.jpg>");
    else if(cardType ==4) {
                        out.println(" <IMG SRC=/WEB-INF/images/motocross.jpg>");
    else if(cardType ==5) {
                        out.println(" <IMG SRC=/WEB-INF/images/Mustang.jpg>");
    else if(cardType ==6) {
                        out.println("<IMG SRC=/WEB-INF/images/Mustang.jpg>");
    out.println("</BODY></HTML>");
         try {
              Class.forName ("com.mysql.jdbc.Driver");
              Connection con = DriverManager.getConnection
              ( url, "*****", "******" );
    Statement stmt = con.createStatement ();
                   stmt.execute (query2);
                   //String query3 = "SELECT LAST_INSERT_ID()";
                   //ResultSet rs = stmt.executeQuery (query3);
                   //int questionID = rs.getInt(1);
                   System.out.println("Total rows:"+questionID);
    stmt.close();
    con.close();
    } // end try
    catch (SQLException ex) {
              //PrintWriter out = resp.getWriter();
         resp.setContentType("text/html");
              while (ex != null) { 
         out.println ("SQL Exception: " + ex.getMessage ());
         ex = ex.getNextException ();
    } // end while
    } // end catch SQLException
    catch (java.lang.Exception ex) {
         //PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");     
              out.println ("Exception: " + ex.getMessage ());
    } // end doGet
    private void printResultSet ( HttpServletResponse resp, ResultSet rs )
    throws SQLException {
    try {
              PrintWriter out = resp.getWriter();
         out.println("<html>");
         out.println("<head><title>jbs jdbc/mysql servlet</title></head>");
         out.println("<body>");
         out.println("<center><font color=AA0000>");
         out.println("<table border='1'>");
         int numCols = rs.getMetaData().getColumnCount ();
    while ( rs.next() ) {
              out.println("<tr>");
         for (int i=1; i<=numCols; i++) {
    out.print("<td>" + rs.getString(i) + "</td>" );
    } // end for
    out.println("</tr>");
    } // end while
         out.println("</table>");
         out.println("</font></center>");
         out.println("</body>");
         out.println("</html>");
         out.close();
         } // end try
    catch ( IOException except) {
    } // end catch
    } // end returnHTML
    } // end jbsJDBCServlet

    I dont know what table names and fields you have but
    say you have a table called XYZ which has a primary
    key field called keyID.
    So in order to get the last row inserted, you could
    do something like
    Select *
    from XYZ
    where keyID = (Select MAX(keyID) from XYZ);
    Good Luckwhat gubloo said is correct ...But this is all in MS SQL Server I don't know the syntax and key words in MYSQL
    This works fine if the emp_id is incremental and of type integer
    Query:
    select      *
    from      employee e,  (select max(emp_id) as emp_id from employee) z
    where      e.emp_id = z.emp_id
    or
    select top 1 * from employee order by emp_id descUday

  • Java.lang.UnsatisfiedLinkError + servlets

    Hi,
    While accessing JNI methods thru Servlets, am getting java.lang.UnsatisfiedLinkError.
    Am I missing on some configuration/deployement steps. Please let me know your thoughts.
    N

    Hi,
    Thanks for the response.
    This is a very peculiar problem. Here, I am able to load the native library by using System.loadlibrary("");
    Invocation of this method goes thru fine without any issues i.e. no exception is thrown.
    But the above mentioned exception is thrwon while invoking any of the native methods present in that libray.
    Any inputs ???
    N

Maybe you are looking for