创建过滤器

Servlet实现了Filter接口,定义了如下方法:

  • init():程序启动时调用此方法,用于初始化该Filter
  • doFilter():客户请求服务器是会经过这里,是具体执行过滤器代码
  • dostory():程序关闭时调用此方法

Filter的生命周期,init()和destroy()方法只被调用一次,doFilter()方法每次有客户端请求就会被调用一次
在这里插入图片描述
创建过滤器类FirstFilter类

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FirstFilter implements Filter {
private FilterConfig filterConfig;
	@Override
	public void destroy() {
		this.filterConfig=null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		try{
			System.out.println("客户端的请求经过这里!!!");
			filterChain.doFilter(request,response);
			System.out.println("账号和密码请求处理经过这里");
		}catch(ServletException e){
			System.out.println("客户端请求失败");
		}catch(IOException io){
			System.out.println("账号和密码请求失败");
		}
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig=filterConfig;
		
	}
	
}

在web.xml中配置过滤器

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <filter>
      		<filter-name>firstFilter</filter-name><!--过滤器名称 -->
      		<filter-class>com.cn.zj.ServletFilter.FirstFilter</filter-class><!--过滤器的实现类 -->
      </filter>
      <filter-mapping>
      	<filter-name>firstFilter</filter-name> <!--映射过滤器名称 -->
      	<url-pattern>/*</url-pattern><!--使用通配符*什么请求都经过滤器 -->
      </filter-mapping>
**index.js页面**
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>创建过滤器</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>		
  			请重新刷卡登录!!!
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44234912/article/details/88666466