Using Commons Logging in JSP Pages

We’ve covered how to use the Commons Logging API within Java components, but we haven’t yet discussed how to use them in JSP pages. There are a number of ways to use the library within JSP pages, but we’ll just cover the two easiest approaches here.

The first approach is to use the same three steps defined earlier, this time performing them in the JSP page itself:

  1. Import the Commons Log and LogFactory classes.

  2. Define and initialize a logger variable for the page.

  3. Start logging.

Example 15-8 illustrates this approach in a basic JSP page.

Example 15-8. Using Commons Logging in a JSP page

<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>

<%-- Get a reference to the logger for this class --%>
<% Log logger = LogFactory.getLog( this.getClass(  ) ); %>

<% logger.debug( "This is a debug message from a jsp" ); %>

<html>
<head>
  <title>Using Commons Logging in a JSP page</title>
</head>

<body>
  <% logger.info( "This is another log message in the jsp" ); %>
  
  There should be two log messages in the log file.
</body>
</html>

You must have the Commons Logging environment configured properly for this to work, just as when using it in the Java classes. Any JSP page that is part of the web application will be able to use the logging utilities. Because most containers use a different class loader for each web application, any JSP page that is not part of the log4j-configured web application may not be able ...

Get Programming Jakarta Struts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.