Servlet that sends Date and Time

Estudies4you
Servlet that sends Date and Time
Example 1: Servlet that sends Date-Time
Let us try these simple hands on. Get the date and time from server.
  • Create following files in a folder (Please check next slide for code)
  • Java File       TimeServlet.java web.xml           Contains logic to display date
  • DD          web.xml            Contains deployment details. Deployment Descriptor
  • Compile the Java File using below command.
    • Please change the path appropriate to your folder structure
    • D:\Tomcat>javac -cp "C: \Program Files\Apache Software Foundation \Tomcat 6.0\lib\servlet-api jar" TimeServlet.java
  • Create below structure with files that you created above
    • Folder "TimeServlet" contains "WEB-INF" Folder
    • I__"WEB-INF" Folder contains "classes" Folder and web.xml File
    • I__"classes" Folder contains "TimeServlet.class" File
  • Deploy the TimeServlet folder inside webapps folder of Tomcat
  • Bounce the Server
  • Send request using "http://localhost:8550/TimeServlet/myTimeServIer
TimeServlet.java: This prepares the response as HTML file that displays date and time on server. For every refresh, you can see change in time
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TimeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{
response.setContentType("text/htmI");
PrintWriter out = response.getWriter();
outprintln("<html>");
out.println("<head>");
out. println("<title> FirstExample! </title>");
out.println("</head>");
out. println("<body>");
out. println("<h1>This is our first servlet example!</h1>");
out. println("Time : "+(new Date()).toLocaleString());
outprintln("</body>");
out. println("</html>");
}             
}

web.xml
  • <servlet> tag maps your servlet class with internal name
  • <servlet-mapping> tag maps internal name with url-pattern that your invoke

<web-app>
<servlet>
<servlet-name>firstexample</servlet-name>
<servlet-class>TimeServlet</servlet-class>
</servlet>
<servlet-mapping>
<serviet-name>firstexample</servlet-name>
<url-pattern>/myTimeServlet</url-pattern>
</servlet-mapping>
</web-app>
  • Output: http://localhost:8550/TimeServlet/myTimeServlet
    • localhost Machine where tomcat is installed
    • 8550 This is the port which is mentioned during installation
    • TimeSevlet Application name (Folder name)
    • myTimeServlet url-pattern provide for servlet in web.xml 
Servlet that sends Date and Time
Re-submit the same url again : you can see the change in time. That shows the response is dynamic and response is server time.



To Top