Client Auto Refresh in Servlets

Ads
 

Client Auto Refresh in Servlets

This section illustrates you how client gets auto refresh.

This section illustrates you how client gets auto refresh.

Client Auto Refresh in Servlets

     

This section illustrates you how client gets auto refresh.

We are providing you an example which explains you clearly. In the example, We have created the session by request.getSession() method. The method response.addHeader("Refresh", "15") refreshes the servlet after every 15 seconds till the servlet gets destroy.

Here is the code of ClientAutoServlet.java

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
  public class ClientAutoServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, 
  HttpServletResponse
 response)
throws ServletException, java.io.IOException {
  HttpSession session = request.getSession();
  Long times = (Long) session.getAttribute("times");
  if (times == null)
  session.setAttribute("times"new Long(0));
  long value = 1;
  if (times != null)
  value = (times.longValue()) + 1;
  if (value < 6)
  response.addHeader("Refresh""15");
  response.setContentType("text/html");
  java.io.PrintWriter out = response.getWriter();
  out.println
  (
"<html><head><title>Client Auto Refresh Example
  </title></head><body>"
);
  out.println
  (
"You've visited this page " + value + " times.");
  session.setAttribute("times"new Long(value));
  out.println("</body></html>");
  
}

In web.xml, do the servlet-mapping

<servlet>
<servlet-name>
ClientAutoServlet</servlet-name>
<servlet-class>
ClientAutoServlet</servlet-class>
</servlet>


<servlet-mapping>
<servlet-name>
ClientAutoServlet</servlet-name> 
<url-pattern>
/ClientAutoServlet</url-pattern>
</servlet-mapping>

Output will be displayed as:

After 15 seconds, page will get refresh. Output will be:

Download Source Code

Ads

Ads