Magazine
 
Tips & Tricks
 
5. Servlet that automatically refreshes
Some times the developer needs to refresh the servlet automatically after some specified time. For example, servlet displaying the scores of the match needs to be refreshed after every little amount of time. This can be done by using the refresh header. Set this header’s value to the number of seconds after which you want the servlet to be refreshed periodically. The code sample showing the concept is given below. This servlet is set to be refreshed after each 10 seconds and displaying the current date and time.

AutoRefreshServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class AutoRefreshServlet extends
HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();
// Set the refresh header
to the desired no of seconds.
res.setHeader(“Refresh”, “10”);
out.println(“<html><body>This page is
refreshed after every 10 seconds.<h3>”);
out.println(new Date().toString());
out.println(“</h3></body></html>”);
}
}

Web.xml

<?xml version=”1.0" encoding=”ISO-8859- 1"?>
<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD
Web Application 2.2//EN”
“http://java.sun.com/j2ee/dtds/webapp_ 2_2.dtd”>
<web-app>
<servlet>

 

<servlet-name>AutoRefreshServlet</servletname>
<servlet-class>AutoRefreshServlet</servletclass>
</servlet>
<servlet-mapping>
<servlet-name>AutoRefreshServlet</servletname>
<url-pattern>/AutoRefreshServlet</urlpattern>
</servlet-mapping>
</web-app>

The output can be seen below:


After 10 seconds the servlet refreshes again and displays the current date and time.



6. Checking password and log information through filter in servlet:

Servlet filters are new component types
introduced in Servlet 2.3 specification. Filters
are java objects that intercepts requests and

Dec 2007 | Java Jazz Up | 75
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 ,

Download PDF