Thursday, April 28, 2011

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("Client Auto Refresh Example<br/> ");
out.println("You've visited this page " + value + " times.");
session.setAttribute("times", new Long(value));
out.println("");
}
}
In web.xml, do the servlet-mapping

ClientAutoServlet
ClientAutoServlet



ClientAutoServlet
/ClientAutoServlet

Output will be displayed as:


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

No comments:

Post a Comment

Translate