[an error occurred while processing this directive]

Display the current date with a Servlet

                         

This servlet program is going to show you how to display a current date and current time on the client browser. 

It is very easy to display current date with the help of a servlet program using the Date class of the java.util package. 

Servlet extends the HttpServlet and overrides the doGet() method that comes from the HttpServlet class. Then server invokes the doGet() method in the case, if the web server receives the GET request from the client. Then the doGet() method passes two arguments first one is HttpServletRequest and second one is HttpServletResponse object. When the client sends the request to the server, in that case server invokes these two objects i.e. HttpServletRequest object and  HttpServletResponse object. 

HttpServletRequest object shows the client's request and the HttpServletResponse object shows the servlet's response.

The doGet() method works like this:

The Servlet  program first uses the setContentType() method that comes from the response object this sets the content type of the response that is text/html i.e. standard MIME content type of the Html pages. The MIME type inform the browser that what type of data to receive. Then  used the method getWriter()  from the response object to retrieve the PrintWriter object. To display the output on the browser  use the println() method that is come from PrintWriter class. 

The code the program is given below:

package myservlets;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DateServlet extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException{

PrintWriter pw = response.getWriter();

Date today = new Date();

pw.println("<html>"+"<body bgcolor=\"#999966\">

<h1>Date and Time with Servlet</h1>");
pw.println("<b>"+ today+"</b></body>"+ "</html>");

}
}

XML File for this program:

<?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_5.xsd"
version="2.5">

<description>
Display current date with help of Servlet
</description>
<display-name>Display current date with help of Servlet</display-name>

<servlet>
<servlet-name>DateServlet</servlet-name>
<servlet-class>myservlets.DateServlet</servlet-class>
</servlet>

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

</web-app>

The output of the program is given below:

Download Source Code

 

                         

[an error occurred while processing this directive]