O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.6. Using log4j in a JSP

Problem

You want to include logging statements in a JSP.

Solution

Design a custom tag that uses log4j to initiate logging messages.

Discussion

A custom tag is an XML element that you invent or design for use in a JSP. In other words, the JSP container does not provide the custom actions; the web developer himself designs the Java classes that provide the tag functionality. A custom tag or action can be used to implement log4j logging functionality in JSPs.

In this recipe, I show:

  • A Java class that provides the tag handler for a custom tag named cbck:log .

  • A Tag Library Descriptor (TLD) that provides the web application with information about the tag.

  • A JSP page that uses the cbck:log tag.

Example 14-9 shows the Java class LoggerTag on which the cbck:log tag is based. Each custom action is actually driven behind the scenes by one or more Java classes. In this case, LoggerTag is like a JavaBean that wraps the log4j classes, which we import at the top of the tag class.

Custom JSP actions are a complex topic, so I explain this tag by focusing mainly on its log4j features. See Chapter 22 to help fill in the missing spaces in your own knowledge about custom tag development.

Example 14-9. A custom tag that uses log4j

package com.jspservletcookbook;import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import java.lang.reflect.Method;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class LoggerTag extends BodyTagSupport {

    

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required