Examples / Server Examples / Servlet JSP Date (Hidden JSP)

Servlet JSP Date (Hidden JSP)

example java server servlets jsp

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;

public class DateServlet extends HttpServlet {

  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);

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

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

Note: Because the date-view.jsp file is inside the WEB-INF directory, the user can’t access it directly.

today's date

Comments and Questions

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!