- public class SampleJdbcServlet extends HttpServlet
- {
- public void doGet(HttpServletRequest req,HttpServletResponse res)
- throws ServletException, IOException
- {
- String user = req.getParameter("user");
- String password = req.getParameter("password");
- String datasource = req.getParameter("datasource");
- res.setContentType("text/html");
- PrintWriter out = res.getWriter();
- out.println("<html><body><pre>");
- try
- {
- Context ctx = new InitialContext();
- out.println("Looking up datasource " + datasource);
- DataSource ds = (DataSource) ctx.lookup(datasource);
- out.println("Establishing connection...");
- out.println("User: " + user + "");
- out.println("Password: " + password);
- Connection con = ds.getConnection(user, password);
- out.println("Connection obtained is: " + con);
- con.close();
- out.println("Connection.isClosed returns: " + con.isClosed());
- }
- catch (SQLException ex)
- {
- out.println("*** SQLException caught ***");
- while (ex != null)
- {
- out.println("Message: " + ex.getMessage ());
- out.println("SQLState: " + ex.getSQLState ());
- out.println("ErrorCode: " + ex.getErrorCode ());
- ex.printStackTrace (out);
- ex = ex.getNextException ();
- }
- }
- catch (java.lang.Exception ex)
- {
- out.println("*** Exception caught ***");
- ex.printStackTrace (out);
- }
- out.println("SampleJdbcServlet finished.");
- out.println("</pre></body></html>");
- out.close();
- }
- }
Raw Paste