Use Filter to Check Date : Filter « Servlet « Java Tutorial






import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;

public class MyServlet implements Filter 
{
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
 
    GregorianCalendar calendar = new GregorianCalendar();
    Date date1 = new Date();
    calendar.setTime(date1);
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    if(hour < 9 || hour > 17) {   
        chain.doFilter(request, response);
    } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>");
        out.println("Get Back to Work!");
        out.println("</TITLE>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<H1>Get Back to Work!</H1>");
        out.println("Sorry, that resource is not available now.");
        out.println("</BODY>");
        out.println("</HTML>");
    }    
  }

  public void destroy() 
  { 
  }

  public void init(FilterConfig filterConfig) 
  {
  }
}
<?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/web-app_2_2.dtd">

<web-app>

  <filter>
    <filter-name>Simple Filter</filter-name>
    <filter-class>MyServlet</filter-class>
    <init-param>
      <param-name>message</param-name>
      <param-value>Hello!</param-value>
    </init-param>    
  </filter>
  <filter-mapping>
    <filter-name>Simple Filter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>  

</web-app>
  Download:  ServletFilterCheckDate.zip( 89 k)








25.17.Filter
25.17.1.Your First Filter
25.17.2.Filter Response
25.17.3.Servlet Filter Init Parameter
25.17.4.Use Filter to log Configuration
25.17.5.Use Filter to check Request Parameter
25.17.6.Use Filter to Check Date
25.17.7.Simple filter for measuring servlet response times
25.17.8.Filter that uses a response wrapper to convert all output to uppercase