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("/WEB-INF/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>
Note: Because the date-view.jsp
file is inside the WEB-INF
directory, the user can’t access it directly.
Use servlets and Jakara Server Pages to show today's date while hiding the JSP file.
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!