[an error occurred while processing this directive]

Use Log in Servlet Context

                         

This section illustrates you how to use log in Servlet Context.

We are providing you an example. In the given example, an object of Servlet Context is defined. The method context.log() writes the specified message to a servlet log file. The name and type of the servlet log file is specific to the servlet container.

 

 

 

 Here is the code of LogInServlet.java

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 LogInServlet extends HttpServlet {
private ServletContext context;

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    context = getServletContext();
    context.log("Hello!");
  }
public void doGet(HttpServletRequest req, 
    HttpServletResponse res)
throws IOException {
    ServletOutputStream out = res.getOutputStream();
    context.log("Your message has been written. ");
    res.setContentType("text/html");
    out.println("<html><head><title>Log in ServletContext</title>
    </head>"
);
    out.println("<body>Go to the tomcat-home\\logs and open 
    the xx file to see your log entries"
);
    out.println("</body></html>");
  }
}

In web.xml, do the following servlet-mapping

<servlet>
<servlet-name>
LogInServlet</servlet-name>
<servlet-class>
LogInServlet</servlet-class>
</servlet>


<servlet-mapping>
<servlet-name>
LogInServlet</servlet-name> 
<url-pattern>
/LogInServlet</url-pattern>
</servlet-mapping>

After deploying the tomcat, Following output will be displayed on the browser

The message provided through the servlet has been written in the log file

Download Source Code

                         
[an error occurred while processing this directive]