Back to: Java Servlets Tutorials
Servlet Debugging with Examples
In this article, I am going to discuss Servlet Debugging with Examples. Please read our previous article where we discussed Server Side Include (SSI) in Servlet with Examples
Servlet Debugging
The testing/debugging phase is one of the toughest aspects of developing servlets. Servlets tend to involve an outsized amount of client/server interaction, making errors likely–but hard to breed. It also can be hard to trace down the explanation for nonobvious errors because servlets don’t work well with standard debuggers, since they run inside a heavily multithreaded and generally complex webserver.
Different ways of Debugging
Here are a couple of hints and suggestions which will aid you in your debugging.
Check the Logs
When you first think there could be a drag, check the logs. Most servers output a mistake log where you’ll find an inventory of all the errors observed by the server and an occasion log where you’ll find a list of interesting servlet events. The event log may also hold the messages logged by the servlets through the log() method, but not always. Note that a lot of servers buffer their output to those logs to enhance performance. When hunting down a problem, you may want to stop this buffering, so you can see problems as they occur. Be sure to reset the buffer size to an inexpensive value afterward.
Example: Servlet Debugging
The Servlet API also provides a simple way of outputting information by using the log() method as below example. The ServletContext logs its text messages to the servlet container’s log file. With Tomcat these logs are found in /logs. The log files do give a sign of the latest emerging bugs or the frequency of problems. For that reason, it’s good to use the log() function within the catch clause of exceptions which should normally not occur.
ContextLog.java
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 version with 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"); java.io.PrintWriter out = response.getWriter( ); String title = "Context Log"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\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 }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>ContextLog</servlet-name> <servlet-class>ContextLog</servlet-class> </servlet> <servlet-mapping> <servlet-name>ContextLog</servlet-name> <url-pattern>/ContextLog</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>ContextLog.java</welcome-file> </welcome-file-list> </web-app>
Output
Run ContextLog.java file, you will get the following output:
Output Extra Information
If you don’t see a sign of the matter within the server’s logs, try having your servlet log extra information with the log() method. During debugging, you’ll add a couple of temporary log() commands as a poor man’s debugger, to urge a general idea of the code execution path and therefore the values of the servlet’s variables. Sometimes it’s convenient to go away the log() commands during a servlet surrounded by if clauses in order that they trigger only a selected debug init parameter are about to true. Extracting the extra information from the server’s logs can at times be unwieldy. To make the temporary debugging information easier to seek out, you’ll have a servlet output its debug information to the client or to a console on the server (through System.out). Not all servers have a console associated with a servlet’s System.out; some redirect the output to file instead.
Use a Standard Debugger
It’s also possible to use a typical debugger to trace down servlet problems, although exactly how won’t be intuitively obvious. After all, you can’t debug a servlet directly because servlets aren’t standalone programs. Servlets are server extensions, and, as such, they need to run inside a server. The servlet runner is often executed from the instruction because of the servlet runner shell script on a UNIX or the servletrunner.exe program on Windows. What servletrunner does is about the classpath to incorporate the acceptable classes then execute java sun.servlet.http.HttpServer. The HttpServer class contains the main() method that listens for incoming requests from servlets. By default, it listens on port 8080.
Examine the Client request
Sometimes when a servlet doesn’t behave, needless to say, it’s useful to seem at the raw HTTP request to which it’s responding. If you’re conversant in the structure of HTTP, you’ll read the request and see exactly where a servlet might get confused. One way to ascertain the raw request is to exchange the online server process with a custom server application that prints out everything it receives.
Create a Custom Client Request
In addition to catching and examining a client’s HTTP request, you may find it useful to create your own HTTP request. You can do this by connecting to the server socket on which the webserver is listening, then manually entering a properly structures HTTP request. To establish the connection, you can use the telnet program, available on all Unix machines and most Windows machines with networking. The telnet program accepts as arguments the host and port number to which it should connect. Once you’re connected, you can make a request that looks like what you saw in the last section. Fortunately, your request is often far simpler – all you would like to specify is that the first line, saying what to urge, and therefore the last line, which must be an empty line that indicates the top of the request.
Important Tips
If all the recommendation thus far hasn’t helped hunt your bug, here are some final recommendations on servlet debugging:
- Use System.getProperty(“java.class.path”) from your servlet to help debug classpath problems. Because servlets are often run from web servers with embedded JVMs, it is often hard sometimes to spot exactly what classpath the JVM is searching. The property “java.class.path” will tell you.
- Be aware that server_root/classes don’t reload and that server_root/servlets probably does.
- Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It’s usually an option under the View menu.
- Make sure the browser isn’t caching a previous request’s output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh.
- Verify that your servlet’s init() method takes a ServletConfig parameter and calls super.init(config) right away.
In the next article, I am going to discuss Servlets Internationalization. Here, in this article, I try to explain Servlet Debugging. I hope you enjoy this Servlet Debugging article.