Auto Refresh in Servlets

The auto-refresh example below demonstrates how to create a save data using sessions after each refresh page. The example increments the counter of the number of times the servlets been accessed in every 5 seconds and displays it as output.


   Example :
    import javax.servlet.*; 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; response.addHeader("Refresh", "5"); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html><head><title>Client Auto Refresh Example</title></head><body>"); out.println("The Counter below will automatically increase after 5 seconds<br/><br/>"); out.println("You've visited this page " + value + " times."); session.setAttribute("times", new Long(value)); out.println("</body></html>"); } }

The method response.addHeader("Refresh", "5") refreshes the servlet after every 5 seconds till the servlet gets destroy. 


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email