How to Debug Servlets
by, 11-28-2011 at 06:07 PM (1584 Views)
Servlets can be difficult to debug because it is not possible to execute them directly. Instead, you trigger their execution by means of an HTTP request, and they are executed by the Web server. For remote execution, inserting break points or reading debugging messages and the stack traces becomes extremely difficult. Here I will outline some strategies to servlet debugging:
- Check the HTML source. If it doesn’t look correct, use the “View Source” command in order to check the HTML. If you can copy the HTML and into a HTML editor or use a formal HTML validator to check your output.
- Always return any error pages to the client. There are times where certain classes of errors can be anticipated by the servlet. In these cases, the servlet should build up descriptive information about the problem and return it to the client in a regular page or by means of the sendError method of HttpServletResponse.
- Run the server from the command line. Most web servers execute as a background process, and this process is often automatically started when the system is booted. If you are having trouble with your servlet, shut it down the server and restarting it from the command line while using a colorizer (if needed) to review the output in the console. You can use this technique and combine it with adding more system output in order to determine where it is failing.
- Use the servlet log file. The HttpServlet class has a method called log that lets you write information into a logging file on the server. The exact location of the log file is server-specific, but it is normally clearly documented or can be found in subdirectories of the server installation directory.
- Check the request data separately. Servlets read data from the HTTP request, construct a response, and send it back to the client. If something in the process goes wrong, you need to verify everything including the whether the client is sending the wrong data. If the data is correct, then you know that there is a problem with how the servlet is processing the data.
- Check your response data. As you have checked your request data, now you’ll want to do the same for the response data! Ensure that you check all the data being sent (i.e. custom HTTP request data, HTTP response headers, etc).
- Stop and restart the server. When you’re debugging a servlet, it’s very easy for the servlet variables to be corrupted when your making changes to low level classes. This is a simple step to ensure that the variables are not corrupted when you’re trying to debug HTML output of your servlet.