4783l3 Listing 3: DailySaying.java, which pulls today's saying from a PostgreSQL database and displays it in our XMLC document. import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; // Bring in the DOM classes which come with Enhydra import org.w3c.dom.html.*; // Bring in the "saying" XMLC class import il.co.lerner.*; public class DailySaying extends HttpServlet { // Keep the connection common to the entire instance private Connection con; // Our "init" method sets up a database connection public void init(ServletConfig config) throws ServletException { // Some private variables for logging into the database String loginJdbc = "org.postgresql.Driver"; String loginUser = "reuven"; String loginPasswd = ""; String loginUrl = "jdbc:postgresql://127.0.0.1/atf"; // Load the PostgreSQL driver try { Class.forName(loginJdbc); con = DriverManager.getConnection(loginUrl, loginUser, loginPasswd); } catch (ClassNotFoundException e) { throw new UnavailableException("Cannot load the PostgreSQL driver: " + e); } catch (SQLException e) { throw new UnavailableException("Error connecting to PostgreSQL: " + e); } } // Our "doGet" method returns an error message indicating // that only "POST" is acceptable. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Set the MIME content type for the response response.setContentType("text/html"); // Get the output stream to STDOUT PrintWriter out = response.getWriter(); try { // Declare our statement Statement statement = con.createStatement(); // Declare and initialize the saying text String saying_text = ""; // Make sure that only one thread handles this // statement at a time synchronized (statement) { String query = "SELECT saying "; query += "FROM DailySayings "; query += "WHERE date = CURRENT_DATE "; // Perform the query ResultSet rs = statement.executeQuery(query); // Iterate through each row of rs (which should // only be one iteration, since date is unique!) while (rs.next()) { saying_text = rs.getString("saying"); } } // Create an instance of our "saying" page object. saying mysaying = new saying(); // Change the text in our "saying" paragraph. mysaying.setTextSaying(saying_text); // Display the results out.println(mysaying.toDocument()); } catch(Exception e) { out.println("" + "" + "DailySaying: Error" + "\n" + "

SQL error in doGet: " + e + "

"); return; } } }