It is always difficult to test or debug Servlets, as they tend to involve a large amount of client-server interaction and errors are common, but very hard to reproduce as a developer.
One of the easiest approach to debug Servlets :
- Using System.out.println() method. This can be used whether a method has been called or not. Also, to print parameter values. Since, this is part of java.lang.System, it is accessed from everywhere.
Debugging Servlets with the support of :
- Message logging
- Log4J
Using Message Logging :
Servlet API provides a simple way of outputting information by using the log() method of ServletContext.
ServletContext context = getServletContext();
context.log("simple log message");
Using Log4J for Debugging Servlets :
Log4j is a reliable, fast and flexible logging framework written in Java, which is distributed under the Apache Software License.
It uses a plugin system that makes it extremely easy to extend the framework by adding appenders, filters, layouts, lookups, etc.
It supports lambda expressions, message objects, internationalization, and custom log levels.
To use Log4j, we need to first download the framework. Once the file has been downloaded, extract the file.
Copy, log4j-api-2.6.1.jar and log4j-core.2.6.1.jar, from the extracted folder and paste the files under WEB-INF/lib folder. Add these files to the Build Path.
We need to provide configuration for the Log4j :
create a simple xml file named ‘log4j2.xml’ under src/ folder.
www.codejava.net/coding/how-to-initialize-log4j-for-java-web-application