Servlet JSP Date (Hidden JSP)

Servlet JSP Date (Hidden JSP)

September 11, 2021

example java server servlets jsp

This example uses servlets and JSP to show today’s date. adds the formatted date to the request and then forwards the request to the JSP file:

package io.happycoding.servlets;

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

JSP Examples


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

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!