LoggingServlet.java Source code

Java tutorial

Introduction

Here is the source code for LoggingServlet.java

Source

// web.xml
/*
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
   <servlet>
  <servlet-name>LoggingServlet</servlet-name>
  <servlet-class>LoggingServlet</servlet-class>
   </servlet>
   <servlet-mapping>
  <servlet-name>LoggingServlet</servlet-name>
  <url-pattern>/loggingServlet</url-pattern>
   </servlet-mapping>
</web-app>
*/

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoggingServlet extends HttpServlet {
    private ServletContext context;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        context = getServletContext();
        context.log("Init has been invoked");
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        ServletOutputStream out = res.getOutputStream();
        context.log("doGet has now been invoked");
        res.setContentType("text/html");
        out.println("<html><head><title>Logging Servlet</title></head>");
        out.println("<body>Visit the <tomcat-home>\\logs and open the xx file to see the log entries");
        out.println("</body></html>");
    }
}