[an error occurred while processing this directive]

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.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

public class AccessedDateServlet extends HttpServlet 
  public void doGet(HttpServletRequest request, HttpServletResponse response
                                          throws ServletException, IOException {
    PrintWriter pw = response.getWriter()
    HttpSession session = request.getSession(true)
    Date create = new Date(session.getCreationTime())
    Date accessed = new Date(session.getLastAccessedTime())
    pw.println("ID " + session.getId())
    pw.println("Create: " + create)
    pw.println("Last Accessed: " + accessed)
    String dataName = request.getParameter("dataName")
    if (dataName != null && dataName.length() 0) {
      String dataValue = request.getParameter("dataValue")
      session.putValue(dataName, dataValue)
    String[] valueNames = session.getValueNames()
    if (valueNames != null &&  valueNames.length > 0) { 
      for (int i = 0; i < valueNames.length; i++) { 
        String str = valueNames[i]
        String str1 = session.getValue(str).toString()
        pw.println(str + " = " + str1)

Download of this program:

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"> -->


Output of this program is given below.


[an error occurred while processing this directive]