Java Reference
In-Depth Information
Example 18−3: Query.java
package com.davidflanagan.examples.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
/**
* This class demonstrates how JDBC can be used within a servlet. It uses
* initialization parameters (which come from the web.xml configuration file)
* to create a single JDBC database connection, which is shared by all clients
* of the servlet.
***/
public class Query extends HttpServlet {
Connection db; // This is the shared JDBC database connection
public void init() throws ServletException {
// Read initialization parameters from the web.xml file
ServletConfig config = getServletConfig();
String driverClassName = config.getInitParameter("driverClassName");
String url = config.getInitParameter("url");
String username = config.getInitParameter("username");
String password = config.getInitParameter("password");
// Use those init params to establish a connection to the database
// If anything goes wrong, log it, wrap the exception and re-throw it
try {
Class.forName(driverClassName);
db = DriverManager.getConnection(url, username, password);
}
catch (Exception e) {
log("Can't create DB connection", e);
throw new ServletException("Query: can't initialize: " +
e.getMessage(), e);
}
}
/** Close the database connection when the servlet is unloaded */
public void destroy() {
try { db.close(); } // Try to close the connection
catch (SQLException e) {} // Ignore errors; at least we tried!
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html"); // We're outputting HTML
PrintWriter out = response.getWriter(); // Where to output it to
// Output document header and a form for entering SQL queries
// When the form is submitted, this servlet is reloaded
out.println("<head><title>DB Query</title></head>\n" +
"<body bgcolor=white><h1>DB Query</h1>\n" +
"<form><b>Query: </b><input name='q'>" +
"<input type=submit></form>");
// See if a query was specified in this request.
String query = request.getParameter("q");
if (query != null) {
Search WWH ::




Custom Search