Listing 4: ShowBlog.java /* A servlet to display the contents of our Weblog ("blog"). The Weblog is stored in a PostgreSQL database table. */ import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class ShowBlog 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://localhost/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(); out.println("Weblog"); out.println("

Weblog

"); try { // Declare our statement Statement statement = con.createStatement(); String query = "SELECT entry_date, entry_headline, "; query += " entry_text "; query += "FROM BlogEntries "; query += "ORDER BY entry_date DESC "; // Perform the query ResultSet rs = statement.executeQuery(query); out.println(""); // Iterate through each row of rs while (rs.next()) { String entry_date = rs.getString("entry_date"); String entry_headline = rs.getString("entry_headline"); String entry_text = rs.getString("entry_text"); out.println("" + "" + "" + "" + ""); } out.println("
" + entry_date + "" + entry_headline + "" + entry_text + "
"); } catch(Exception e) { out.println("" + "" + "ShowBlog: Error" + "\n" + "

SQL error in doGet: " + e + "

"); return; } } }