1

I am having difficulty with getting this work. I can connect to the database without problem, however I can not make it show me the html page. It does not run.

import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowBedrock extends HttpServlet 
{
    public String getServletInfo()
    {
       return "Servlet connects to PostgreSQL database and displays result of a SELECT";
    }

    private Connection dbcon;  // Connection for scope of ShowBedrock

    // "init" sets up a database connection
    public void init(ServletConfig config) throws ServletException
    {
        String loginUser = "postgres";
        String loginPasswd = "supersecret";
        String loginUrl = "jdbc:postgresql://localhost/bedrock";

        // Load the PostgreSQL driver
        try 
        {
              Class.forName("org.postgresql.Driver");
              dbcon = DriverManager.getConnection(loginUrl, loginUser, loginPasswd);
        }
        catch (ClassNotFoundException ex)
        {
               System.err.println("ClassNotFoundException: " + ex.getMessage());
               throw new ServletException("Class not found Error");
        }
        catch (SQLException ex)
        {
               System.err.println("SQLException: " + ex.getMessage());
        }
    }

    // Use http GET

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");    // Response mime type

        // Output stream to STDOUT
        PrintWriter out = response.getWriter();

        out.println("<HTML><Head><Title>Bedrock</Title></Head>");
        out.println("<Body><H1>Bedrock</H1>");

        try
        {
                // Declare our statement
                Statement statement = dbcon.createStatement();

                String query = "SELECT name, dept, ";
                query +=       "       jobtitle ";
                query +=       "FROM   employee ";

                // Perform the query
                ResultSet rs = statement.executeQuery(query);

                out.println("<table border>");

                // Iterate through each row of rs
                while (rs.next())
                {
                   String m_name = rs.getString("name");
                   String m_dept = rs.getString("dept");
                   String m_jobtitle = rs.getString("jobtitle");
                   out.println("<tr>" + 
                               "<td>" + m_name + "</td>" +
                               "<td>" + m_dept + "</td>" +
                               "<td>" + m_jobtitle + "</td>" +
                               "</tr>");
                }

                out.println("</table></body></html>");
                statement.close();
        }
        catch(Exception ex)
        {
                out.println("<HTML>" +
                            "<Head><Title>" +
                            "Bedrock: Error" +
                            "</Title></Head>\n<Body>" +
                            "<P>SQL error in doGet: " +
                            ex.getMessage() + "</P></Body></HTML>");
                return;
        }
        out.close();
    }
}

I get the following error any body knows why?:

javax.servlet.ServletException: Class not found Error
    ShowBedrock.init(ShowBedrock.java:42)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    java.lang.Thread.run(Unknown Source)


note The full stack trace of the root cause is available in the Apache Tomcat/6.0.35 logs.
2
  • 1
    While this isn't an answer, I do have a suggestion: Don't use the PostgreSQL JDBC driver directly. Use a connection pool like C3P0, proxool, etc. In EE application servers one is built in and provided for you by the app server; I don't know if that's the case in Tomcat. You'll have a lot less trouble with resource waste and connection overhead if you use a connection pool. Commented Apr 21, 2012 at 5:14
  • Don't use ex.getMessage() but ex.printStackTrace(). Or better use Log4J or some similar library for logging your errors. Commented Apr 21, 2012 at 6:39

3 Answers 3

1

I get the following error any body knows why?

The reason why you are getting that error body is that your handler for ClassNotFoundException is throwing away the original exception stacktrace. You are writing the original exception's message to System.err but (obviously) that won't go into the normal system logs. (You'll probably find find the message in the "catalina.out" file ... depending on how Tomcat is configured / launched.)

The right way to do this is to either chain the exception; e.g.

    throw new ServletException("Class not found Error", e);

or log it explicitly at the point that you catch it. And if you do log it explicitly, make sure that you log the exception, and not just the exception message.


We can't tell you the actual root cause of the problem unless we see the original exception stacktrace ... but the two most likely causes are:

  • The classloader can't find a class that is needed; e.g. because the JAR file is not in the right place.
  • Class initialization failed for some class during the initialization of the class that you are attempting to load.
Sign up to request clarification or add additional context in comments.

Comments

1

Tomcat expects that your servlet will be in a package. Yours appears to be in the default package; please add one and recompile. I'll bet things will go better for you then.

Tomcat 6 and 7 expect to find JDBC JARs in the server /lib directory. Add your PostgreSQL JDBC JAR to the server /lib location.

3 Comments

Hi, thanks for your reply. I tried it, did not do the trick and all my servlets work in default package without any problems.
I forgot to do it and this comment saved my life! Thank you.
Glad to help. Good luck.
0

Seem you did't add Postgresql JDBC driver into classpath, as the following error suggest:

javax.servlet.ServletException: Class not found Error

Which is origin from:

throw new ServletException("Class not found Error");

You can download Postgresql JDBC driver and put in PROJECT/WEB-INF/lib folder.

Suggestion

One suggestion, your exception handling is wrong, you should change

throw new ServletException("Class not found Error");

to

throw new ServletException("Class not found Error", e);

1 Comment

But, it is there in WEB-INF/lib

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.