YouTip LogoYouTip

Servlet Debugging

Servlet Debugging | Tutorial

Testing and debugging Servlets is always a challenging part of the development process. Servlets often involve extensive client/server interactions, which can lead to errors that are difficult to reproduce.

Here are some tips and suggestions to help you debug.

System.out.println() is used as a marker to test whether a specific piece of code is executed. We can also print the values of variables. Additionally:

  • Since the System object is part of the core Java objects, it can be used anywhere without needing to install any additional classes. This includes Servlets, JSP, RMI, EJBs, regular Beans and classes, and standalone applications.
  • Unlike stopping at a breakpoint, writing to System.out does not interfere with the normal execution flow of the application, making it particularly valuable when timing is critical.

Here is the syntax for using System.out.println():

System.out.println("Debugging message");

All messages generated by the above syntax will be recorded in the web server's log file.

It is a very good idea to use appropriate logging methods to record all debugging, warning, and error messages. It is recommended to use log4J to log all messages.

The Servlet API also provides a simple way to output information using the log() method, as shown below:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ContextLog extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        String par = request.getParameter("par1");

        // Call the two ServletContext.log methods
        ServletContext context = getServletContext( );
        if (par == null || par.equals(""))
            // Log with a Throwable parameter
            context.log("No message received:",
                new IllegalStateException("Missing parameter"));
        else
            context.log("Here is the visitor's message: " + par);

        response.setContentType("text/html;charset=UTF-8");
        java.io.PrintWriter out = response.getWriter( );
        String title = "Context Log";
        String docType = "<!DOCTYPE html> \n";
        out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor=\"#f0f0f0\">\n" +
            "<h1 align=\"center\">" + title + "</h1>\n" +
            "<h2 align=\"center\">Messages sent</h2>\n" +
            "</body></html>");
    } //doGet
}

ServletContext logs its text messages to the Servlet container's log file. For Tomcat, these logs can be found in the <Tomcat-installation-directory>/logs directory.

These log files indeed give an indication of the frequency of newly occurring errors or problems. For this reason, it is recommended to use the log() function in catch clauses for exceptions that would not normally occur.

You can debug a Servlet using the jdb command used for debugging applets or applications.

To debug a Servlet, we can debug sun.servlet.http.HttpServer and then treat it as the HttpServer executing the Servlet in response to HTTP requests from the browser. This is very similar to debugging an applet. Unlike debugging an applet, the program actually being debugged is sun.applet.AppletViewer.

Most debuggers automatically hide the details of how to debug an applet. Similarly, for servlets, you must help the debugger perform the following actions:

  • Set your debugger's classpath so that it can find sun.servlet.http.HttpServer and the related classes.
  • Set your debugger's classpath so that it can find your servlet and its supporting classes, typically in server_root/servlets and server_root/classes.

You usually do not want server_root/servlets in your classpath because it disables servlet reloading. However, this inclusion rule is very useful for debugging. It allows your debugger to set breakpoints in the servlet before the custom Servlet loader in HttpServer loads the Servlet.

If you have set the correct classpath, you can start debugging sun.servlet.http.HttpServer. You can set breakpoints in the Servlet code you want to debug, and then make a request to the HttpServer through a web browser using the given Servlet (e.g., http://localhost:8080/servlet/ServletToDebug). You will see the program execution stop at the breakpoint.

Comments in the code are helpful for debugging in various ways. Comments can be used in many other ways during the debugging process.

This Servlet uses Java comments and single-line comments (//...). Multi-line comments (/* ...*/) can be used to temporarily remove parts of Java code. If the bug disappears, take a closer look at the code you just commented out to find the problem.

Sometimes, when a Servlet is not behaving as expected, it is very useful to look at the raw HTTP request and response. If you are familiar with the HTTP structure, you can read the request and response to see what these headers actually are.

Below are some tips for Servlet debugging:

  • Note that server_root/classes will not be reloaded, while server_root/servlets may be.
  • Ask the browser to display the raw content of the page it is displaying. This helps identify formatting issues. It is usually an option under the "View" menu.
  • Ensure the browser has not cached the output of a previous request by forcing a complete page reload. In Netscape Navigator, use Shift-Reload; in Internet Explorer, use Shift-Refresh.
  • Confirm that the servlet's init() method accepts a ServletConfig parameter and calls super.init(config).
← Servlet InternationalizationServlet Packaging β†’