Servlets Auto Page Refresh

Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your web page regularly using referesh or reload button with your browser.

Java Servlet makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.

The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method:

public void setIntHeader(String header, int headerValue)

This method sends back header “Refresh” to the browser along with an integer value which indicates time interval in seconds.

Auto Page Refresh Example:

This example shows how a servlet performs auto page refresh using setIntHeader() method to set Refresh header.

 

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CounterServlet extends HttpServlet{
  public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException, IOException {
  HttpSession session = request.getSession(true);
  response.setIntHeader("Refresh", 5);
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  Integer count = new Integer(0);
  String head;
  if (session.isNew()) {
  head = "This is the New Session";
  } else {
  head = "This is the old Session";
  Integer oldcount =(Integer)session.getValue("count"); 
  if (oldcount != null) {
  count = new Integer(oldcount.intValue() + 1);
  }
  }
  session.putValue("count", count);
  out.println("<HTML><BODY BGCOLOR="#FDF5E6">n" +
  "<H2 ALIGN="CENTER">" + head + "</H2>n" + 
  "<TABLE BORDER=1 ALIGN=CENTER>n"
  + "<TR BGCOLOR="#FFAD00">n" 
  +"  <TH>Information Type<TH>Session Countn" 
  +"<TR>n" +" <TD>Total Session Accessesn" +
  "<TD>" + count + "n" +
  "</TABLE>n" 
  +"</BODY></HTML>" );
  }
}
Servlets Auto Page Refresh

 

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next