如何在JSP中使用过滤器?
以下示例演示了如何每次访问任何JSP文件时都打印客户端的IP地址和当前日期时间。此示例将为您提供对JSP过滤器的基本了解,但您可以使用相同的概念编写更复杂的过滤器应用程序:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Implements Filter class
public class LogFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
// Get init parameter
String testParam = config.getInitParameter("test-param");
//Print the init parameter
System.out.println("Test Param: " + testParam);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws java.io.IOException, ServletException {
// Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();
// Log the IP address and current timestamp.
System.out.println("IP "+ ipAddress + ", Time "+ new Date().toString());
// Pass request back down the filter chain
chain.doFilter(request,response);
}
public void destroy( ) {
/* Called before the Filter instance is removed
from service by the web container*/
}
}以通常的方式编译**LogFilter.java**并将您的**LogFilter.class**文件放入**<Tomcat安装目录>/webapps/ROOT/WEB-INF/classes**。
JSP过滤器映射在web.xml中
过滤器被定义,然后映射到URL或JSP文件名,这与Servlet定义并映射到**web.xml**文件中的URL模式的方式非常相似。在部署描述符文件**web.xml**中创建以下过滤器标签条目:
<filter> <filter-name>LogFilter</filter-name> <filter-class>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>
由于我们在配置中指定了**/***,因此上述过滤器将应用于所有servlet和JSP。如果您只想将过滤器应用于少数servlet或JSP,则可以指定特定的servlet或JSP路径。
现在尝试调用任何servlet或JSP,您将在Web服务器日志中看到生成的日志。您可以使用**Log4J记录器**将上述日志记录到单独的文件中。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP