Sunday, 25 March 2018

Servlet program to Auto Web Page Refresh


2. Write a JAVA Servlet Program to Auto Web Page Refresh(Consider a webpage which is displaying Date and time or stock market status. For all such type of pages, you would need to refresh your web page regularly; Java Servlet makes this job easy by providing refresh automatically after a given interval).

Index.html
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
         <form method="post" action="Refresh" >
        <input type="submit" value="Login" />
    </body>
</html>

Refresh.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 // Extend HttpServlet class public class Refresh extends HttpServlet
{
   // Method to handle GET method request.
  public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set refresh, autoload time as 5 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();
      String title = "Auto Page Refresh using Servlet";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n"+
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<h1 align=\"center\">" + title + "</h1>\n" +
        "<p>Current Time is: " + CT + "</p>\n");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}
OUTPUT:



No comments:

Post a Comment

PUBLISHER & SUBSCRIBER PATTERN

Using the UML Drawing Tool by implementing the code in Java demonstrate the Observer  Design Pattern. The Publisher-Subscriber desig...