Skip to main content

Servlet Program to get current date

Servlet Program to get current date and time.
Steps:

  • Create servlet by extending Httpservlet
  • Configure Servlet URL in Web.xml
  • Run Servlet
MyFirstServlet.java

package com.jspiders.studentsapp.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyFirstServlet 
extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, 
                         HttpServletResponse resp)
	throws ServletException, IOException 
	{
		
		System.out.println("Inside Get() Method ...");
		
		//Java Code to Generate Current Date & Time
		Date dateRef = new Date();
		String currentDate = dateRef.toString();
		
		resp.setContentType("text/html");
		PrintWriter out=resp.getWriter();
		
		out.print("Today's date: "+currentDate);
		
		
	}//End of Get method
	
}//End of Class

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
id="WebApp_ID" version="2.5">
 
 <welcome-file-list>
 <welcome-file>currentDate</welcome-file>
 <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 
 
 <servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>com.spy.javaforlearn.servlets.MyFirstServlet</servlet-class>
 </servlet>

 <servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/currentDate</url-pattern>
 </servlet-mapping>
 
</web-app>
Run the servlet in apache tomcat server
currentdate