TEXT   165
public class SampleJdbcServlet extends HttpServlet
Guest on 2nd December 2024 06:48:44 PM


  1. public class SampleJdbcServlet extends HttpServlet
  2. {
  3.   public void doGet(HttpServletRequest req,HttpServletResponse res)
  4.     throws ServletException, IOException
  5.   {
  6.     String user = req.getParameter("user");
  7.     String password = req.getParameter("password");
  8.     String datasource = req.getParameter("datasource");
  9.     res.setContentType("text/html");
  10.     PrintWriter out = res.getWriter();
  11.     out.println("<html><body><pre>");
  12.     try
  13.     {
  14.       Context ctx = new InitialContext();
  15.  
  16.       out.println("Looking up datasource " + datasource);
  17.       DataSource ds = (DataSource) ctx.lookup(datasource);
  18.  
  19.       out.println("Establishing connection...");
  20.       out.println("User: " + user + "");
  21.       out.println("Password: " + password);
  22.  
  23.       Connection con = ds.getConnection(user, password);
  24.       out.println("Connection obtained is: " + con);
  25.  
  26.       con.close();
  27.       out.println("Connection.isClosed returns: " + con.isClosed());
  28.     }
  29.     catch (SQLException ex)
  30.     {
  31.       out.println("*** SQLException caught ***");
  32.       while (ex != null)
  33.       {
  34.         out.println("Message: " + ex.getMessage ());
  35.         out.println("SQLState: " + ex.getSQLState ());
  36.         out.println("ErrorCode: " + ex.getErrorCode ());
  37.         ex.printStackTrace (out);
  38.         ex = ex.getNextException ();
  39.       }
  40.     }
  41.     catch (java.lang.Exception ex)
  42.     {
  43.       out.println("*** Exception caught ***");
  44.       ex.printStackTrace (out);
  45.     }
  46.  
  47.     out.println("SampleJdbcServlet finished.");
  48.     out.println("</pre></body></html>");
  49.     out.close();
  50.   }
  51. }

Raw Paste

Login or Register to edit or fork this paste. It's free.