Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Servlet – Auto Page Refresh

  • Last Updated : 13 Jan, 2022

The public service(HttpServletRequest req, HttpServletResponse res) method in the servlet component should extend HttpServlet (AC). It allows the browser to refresh the web page when a certain amount of time has passed. Auto-refresh can be enabled in two ways:

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

“refresh” is fixed in these approaches. Time is passed to the setHeader() method as a string, while time is passed to the setIntHeader() method as an int number. The time should be expressed as a fraction of a second.

Example:

setIntHeader("Refresh", 5);

Auto Page Refresh Example

This is the PageRefresh.java file where we have written page refresh logic code

Java




import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
  
public class PageRefresh extends HttpServlet
{
     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     {
          // Set refresh time as 1 seconds
          response.setIntHeader("Refresh", 5);
  
          // Set response content type
          response.setContentType("text/html");
  
          // Get current time
          Calendar calendar = new GregorianCalendar();
          String am_pm;
          int hour = calendar.get(Calendar.HOUR);
          int minute = calendar.get(Calendar.MINUTE);
          int second = calendar.get(Calendar.SECOND);
          if(calendar.get(Calendar.AM_PM) == 0)
          {
               am_pm = "AM";
          }
          else
          {
               am_pm = "PM";
          }
          String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
      
          PrintWriter out = response.getWriter();
        
          out.println("<h1 align='center'>Auto Refresh Page</h1>");
          out.println("<h2 align='center'>Current time: "+CT+"</h2>");
     }
     // Handle POST method request.
     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     {
          doGet(request, response);
     }
}

Following is the web.xml file:

XML




<web-app>
 <servlet>
     <servlet-name>PageRefresh</servlet-name>
     <servlet-class>PageRefresh</servlet-class>
 </servlet>
   
 <servlet-mapping>
     <servlet-name>PageRefresh</servlet-name>
     <url-pattern>/PageRefresh</url-pattern>
 </servlet-mapping>
</web-app>

Output:

It refreshes the browser every five seconds and the current time will be changed automatically.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!