本篇文章是个人再学习的时候觉得Filter中一些思考。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>过滤器参数</title>
</head>
<body>
<h1>欢迎光临,<br>
<!-- 所以的全局变量是保存在application对象中 -->
您是本站第<%=application.getAttribute("count") %>
位访客。
</h1>
</body>
</html>
因为application对象里保存了整个服务器的全局变量,因此可以通过
getAttribute()方法获取相关参数,程序在执行到这里的时候,会在配置文件web.xml中寻找"count"这个参数。
<filter>
<filter-name>HelloFilter</filter-name>
<filter-class>com.felay.filter.HelloFilter</filter-class>
<!-- 为Filter中的属性赋初值 -->
<init-param>
<param-name>count</param-name>
<!-- 初始化参数 -->
<param-value>5000</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>HelloFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
但是由于count是被封装在filter里的,因此必须通过index.jsp--->HelloFilter的映射找到具体的类com.felay.filter.HelloFilter,然后进入到该类中,下面是我写的Filter类
package com.felay.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
public class HelloFilter implements Filter {
//访问数量,其初始值从配置文件中设置,其原因是维护更方便
private int count;
public HelloFilter() {
}
public void destroy() {
}
public void init(FilterConfig fConfig) throws ServletException {
//从配置文件中读取参数
String param = fConfig.getInitParameter("count");
count=Integer.parseInt(param);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
count++;
//将ServletRequest转换成HttpServletRequest才能对其进行处理
HttpServletRequest req = (HttpServletRequest) request;
//获取ServletContext上下文
ServletContext context = req.getSession().getServletContext();
context.setAttribute("count", count);
chain.doFilter(request, response);
}
//对Filter进行初始化 FilterConfig类实例是从web.xml配置文件中读取初始化数据
}
由于请求是http协议经过这个过滤器,必须要进行初始化操作,当参数通过FilterConfig类实例读取到web.xml配置文件中的count参数后,读取到了其值为5000,然后才会调用doFilter()方法对参数的逐级传递。知道application对象获取到指到的属性值。