Auto Refresh Page in Servlet

Auto Refresh Page in Servlet | We can give instructions to the browser along with response with the support of response header “refresh” to enable auto-refresh the web page.

The auto-refresh feature is available in the HttpServlet abstract class, and we must use a service(HttpServletRequest req, HttpServletResponse res) method or 7 doXxx(-,-) method which accepts the HTTP protocol.

In the servlet component, public service(HttpServletRequest req, HttpServletResponse res) method should extend HttpServlet (AC). It allows the browser to refresh the web page after a given interval.

There are two methods to enable auto-refresh.

  • setHeader(“refresh”, String “<time-in-second>”)
  • setIntHeader(“refresh”, int <time-in-second>)

In these methods “refresh” is fixed. The setHeader() method takes time as a string, whereas the setIntHeader() method takes time as an int value. The time should be in seconds.


res.setHeader(“refresh”, “10”);
res.setIntHeader(“refresh”, 10);

Auto-Refresh on the web page is very useful while displaying live game scores, stock market share values, stock market share values, random advertisements, and e.t.c.

Response headers are part of the generated response to the browser giving instruction to the browser towards displaying the web pages. Some response headers are contentType, refresh, location, server, and e.t.c.

Write an Application to Auto Refresh a Page in Servlet

Servlet Example to Display Time and Date through Auto Refresh Feature

In this servlet component, we will use auto-refresh features, so that it can update the page after every 5 seconds and we can get the updated result. You can use this servlet example and modify the required details.


import jakarta.servlet.*;
import jakarta.servlet.http.*;

public class AutoRefreshServlet extends HttpServlet {
 public void service(HttpServletRequest req, HttpServletResponse res)
         throws ServletException, IOException {

     // set content type

     // get stream object
     PrintWriter pw = res.getWriter();

     // display date and time
     pw.println("<h1>Date and time :: " 
                + new java.util.Date() + "</h1>");

     // auto refresh after every 3 second
     res.setIntHeader("refresh", 3);

     // close stream

In the servlet configuration file (web.xml),



See the code at GitHub. Give request to the servlet component through, we will get updated result after every 3 seconds.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply