Servlet JSP Date



Servlet JSP Date


This example uses servlets and JSP to show today’s date.

DateServlet.java adds the formatted date to the request and then forwards the request to the JSP file:

package io.happycoding.servlets;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.ServletException;

@WebServlet("/date")
public class DateServlet extends HttpServlet {

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

    SimpleDateFormat dateFormat =
        new SimpleDateFormat("hh:mm aa 'on' EEEE, MMMM dd, yyyy");
    Date now = new Date();
    String formattedDate = dateFormat.format(now);

    request.setAttribute("date", formattedDate);
    request.getRequestDispatcher("/date-view.jsp").forward(request,response);
  }
}

date-view.jsp uses expression language (EL) to get the formatted date from the request, and outputs it in HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Current Time</title>
  </head>
  <body>
    <h1>Current Time</h1>
    <p>The current time is ${date}</p>
  </body>
</html>

today's date



JSP Examples