[1] JSP里的一个最简单的过滤器(filter)的例子

120 阅读1分钟

一个每隔五秒钟自动刷新的jsp页面:

<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%    response.setIntHeader("Refresh", 5);    
      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;    
	  out.println("Current Time is: " + CT + "\n"); 
%>
</center>
</body>
</html>

在开发包com.sap.jerry中创建新的filter:

package com.sap.jerry;

import javax.servlet.*;
import java.util.*;

public class LogFilter implements Filter  {
	   public void  init(FilterConfig config) 
	                         throws ServletException{
	      // 获取初始化参数
	      String testParam = config.getInitParameter("test-param"); 
	 
	      //打印初始化参数
	      System.out.println("Test Param: " + testParam); 
	   }
	   public void  doFilter(ServletRequest request, 
	                 ServletResponse response,
	                 FilterChain chain) 
	                 throws java.io.IOException, ServletException {
	 
	      // 获取客户端ip地址  
	      String ipAddress = request.getRemoteAddr();
	 
	      // 输出ip地址及当前时间
	      System.out.println("IP "+ ipAddress + ", Time "
	                                       + new Date().toString());
	 
	      // 传递请求道过滤器链
	      chain.doFilter(request,response);
	   }
	   public void destroy( ){
	      /* 在Filter实例在服务器上被移除前调用。*/
	   }
	}

在WebContent/WEB-INF文件夹下的web.xml里,添加filter的声明:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>jerryjsp</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	
	  
	<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>com.sap.jerry.LogFilter</filter-class>
   <init-param>
	  <param-name>test-param</param-name>
	  <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

之后即可在console页面里观察到filter类打印的输出:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":