Filter过滤器的简单流程

本文详细介绍了Java Web应用中过滤器的工作原理及其实现过程。通过一个具体示例,展示了如何利用过滤器来记录网站访问次数,并将其保存在全局变量中。文章还深入探讨了过滤器的配置方式及其在web.xml文件中的映射。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇文章是个人再学习的时候觉得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对象获取到指到的属性值。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值