Accessing Date In Servlet
In this example, we are going to show how we can display a creation date of the session and last accessed date or time and id on our browser. It is very easy to display it on our browser by using the Date class of the java.util package.
As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. The server invokes doGet() method whenever web server receives the GET request from the servlet. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException.
getSession(): getSession() is a method. This is the method that uses HttpServletRequest object. When you call the method with its argument as true, the servlet reference implementation creates a session if necessary. To properly maintain the session, you must call getSession() before any output to response.
getCreationTime(): getCreationTime() is a method. This is the method that returns the time when this session was created a long integer time.
getLastAccessedTime(): getLastAccessedTime() is a method. This is the method that returns the last time the client sends request with this session.
getId(): This is the method that returns a string containing the unique identifier assigned to this session.
Here is the code of this program:
import java.io.*;
|
XML file for this program:
<?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>amar</servlet-name> <servlet-class>AccessedDateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>amar</servlet-name> <url-pattern>/AccessedDateServlet</url-pattern> </servlet-mapping> </web-app> |
Output of this program is given below.