How to use the context log in servlets?
>> Monday, June 13, 2011
This example illustrates about how to use of Context Log in servlet.
Context Log is used to write specified message to server log file when servlet is called.
In the following JSP page (message.jsp) we have simply taken a text area where user give,
his/her message and post the form. After posting the form, the servlet ContextLogExample is called.
Source code of the message.jsp is given below:
message.jsp
<%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1"%> Context Log is used to write specified message to server log file when servlet is called.
In the following JSP page (message.jsp) we have simply taken a text area where user give,
his/her message and post the form. After posting the form, the servlet ContextLogExample is called.
Source code of the message.jsp is given below:
message.jsp
<br>
<form name="frm" method="post" action=../ContextLogExample>
<table border = "0">
<tr align="left" valign="top">
<td>Give your Message:</td>
</tr>
<tr>
<td><TEXTAREA NAME="message" COLS=30 ROWS=6></TEXTAREA></td>
</tr>
<tr align="left" valign="top">
<td><input type="submit" name="submit" value="submit"/></td>
</tr>
</table>
</form>
when we run the program we will get output as below
In the following servlet (ContextLogExample) we get parameter of jsp page in "message"
variable and set this message to the log file by log() method of ServletContext interface
ContextLogExample.java:
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class ContextLogExample extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String message = request.getParameter("message"); ServletContext context = getServletContext(); if(message == null || message.equals("")){ context.log("No message received:", new IllegalStateException("Parameter not Found")); }else{ context.log("Parameter Found: Successfully received your message: " + message); } out.println("<html><head><title>Context Log Example</title></head><body>"); out.println("<h2><font color='green'>Successfully send your Message</font></h2>"); out.println("</body></html>"); } }
web.xml
<servlet> <servlet-name>ContextLogExample</servlet-name> <servlet-class>ContextLogExample</servlet-class> </servlet> <servlet-mapping> <servlet-name>ContextLogExample</servlet-name> <url-pattern>/ContextLogExample</url-pattern> </servlet-mapping>
User enter the message as below
Servlet sets the message in the log file which is shown like below:
0 comments:
Post a Comment