Servlet过滤器从字面上的字意理解为景观一层次的过滤处理才达到使用的要求,而其实Servlet过滤器就是服务器与客户端请求与响应的中间层组件,在实际项目开发中Servlet过滤器主要用于对浏览器的请求进行过滤处理,将过滤后的请求再转给下一个资源。
过滤器的基本概念
Filter是在Servlet 2.3之后增加的新功能,当需要限制用户访问某些资源或者在处理请求时提前处理某些资源的时候,就可以使用过滤器完成。
过滤器是以一种组件的形式绑定到WEB应用程序当中的,与其他的WEB应用程序组件不同的是,过滤器是采用了“链”的方式进行处理的。

实现过滤器
在Servlet中,如果要定义一个过滤器,则直接让一个类实现javax.servlet.Filter接口即可,此接口定义了三个操作方法:
- public void init(FilterConfig filterConfig) throws ServletException
- public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException
- public void destroy()
FilterChain接口的主要作用是将用户的请求向下传递给其他的过滤器或者是Servlet:
- public void doFilter(ServletRequest request,ServletResponse response) throws IOException,ServletException
在FilterChain接口中依然定义了一个同样的doFilter()方法,这是因为在一个过滤器后面可能存在着另外一个过滤器,也可能是请求的最终目标(Servlet),这样就通过FilterChain形成了一个“过滤链”的操作,所谓的过滤链就类似于生活中玩的击鼓传花游戏
定义一个简单的过滤器 —— SimpleFilter.java
package com.oumyye.过滤器;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 SimpleFilter implements Filter { public void init(FilterConfig config) throws ServletException { // 初始化过滤器 String initParam = config.getInitParameter("ref"); // 取得初始化参数 System.out.println("** 过滤器初始化,初始化参数 = " + initParam); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 执行过滤 System.out.println("** 执行doFilter()方法之前。"); chain.doFilter(request, response); // 将请求继续传递 System.out.println("** 执行doFilter()方法之后。"); } public void destroy() { // 销毁过滤 System.out.println("** 过滤器销毁。"); }}
配置web.xml
<filter> <filter-name>simple</filter-name> <filter-class>com.oumyye.过滤器.SimpleFilter</filter-class>
<init-param>
<param-name>ref</param-name>
<param-value>HELLOMLDN</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>simple</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
过滤器的应用 —— 编码过滤
在进行WEB开发中,编码过滤是必不可少的操作,如果按照之前的做法,在每一个JSP或者是Servlet中都重复编写“request.setCharacterEncoding("UTF-8")”的语句肯定是不可取的,会造成大量的代码重复,那么此时就可以通过过滤器完成这种编码过滤。
package com.oumyye.过滤器;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 EncodingFilter implements Filter { private String charSet; // 设置字符编码 public void init(FilterConfig config) throws ServletException { this.charSet = config.getInitParameter("charset"); // 取得初始化参数 } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding(this.charSet); // 设置统一编码 } public void destroy() {
}}
配置web.xml文件
<filter> <filter-name>encoding</filter-name> <filter-class>com.oumyye.过滤器.EncodingFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
过滤器的应用---登陆验证
登陆验证是所有WEB开发中不可缺少的部分,最早的做法是通过验证session的方式完成,但是如果每个页面都这样做的话,则肯定会造成大量的代码重复,而通过过滤器的方式就可以避免这种重复的操作。
在这里需要注意的是,session本身是属于HTTP协议的范畴,但是doFilter()方法中定义的是ServletRequest类型的对象,那么要想取得session,则必须进行向下转型,将ServletRequest变为HttpServletRequest接口对象,才能够通过getSession()方法取得session对象。
package com.oumyye.过滤器;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;public class FilterLogin extends HttpServlet implements Filter { private FilterConfig filterConfig; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { HttpSession session=((HttpServletRequest)request).getSession(); response.setCharacterEncoding("gb2312"); //响应客户端类型 if(session.getAttribute("user")==null){ //判断session中是否有user这个对象 PrintWriter out=response.getWriter(); //创建一个输出流 //如果为空则通过javaScript脚本出输出提示并跳转到index.jsp页面 out.print("<script language=javascript>alert('您还没有登录!!!');window.location.href='../index.jsp';</script>"); }else{ filterChain.doFilter(request, response);//否则继续执行 } } public void destroy() { }}
User.java
package com.mr.filter;public class User { private String username; private String password; public String getUsername() { return username; } public String getPassword() { return password; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; }}
配置web.XML
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list><filter> <filter-name>filterUser</filter-name> <filter-class>com.oumyye.过滤器.FilterLogin</filter-class> </filter> <filter-mapping> <filter-name>filterUser</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
jsp页面:
index.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><link href="css/style.css" rel="stylesheet" type="text/css" ><script language="javascript" type="">function checkEmpty(){if(document.form.name.value==""){alert("用户名不能为空")document.form.name.focus();return false;}if(document.form.password.value==""){alert("密码不能为空")document.form.password.focus();return false;}}</script><title>使用过滤器身份验证</title></head><body> <h3> </h3> <p align="center">使用过滤器身份验证</p> <form name="form" method="post" action="loginresult.jsp" onSubmit="return checkEmpty()"><table width="220" border="1" align="center" cellpadding="0" cellspacing="0" bgcolor="808080"> <tr> <td align="center">用户名:</td> <td ><input name="name" type="text"></td> </tr> <tr> <td align="center">密 码:</td> <td><input name="password" type="password"></td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" name="Submit" value="登录"> <input type="submit" value="退出"/> </td> </tr></table><br></form></body></html>
loginresult.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" %><%@ page import="com.mr.filter.User"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>使用过滤器身份验证</title></head><%request.setCharacterEncoding("gb2312");String name=request.getParameter("name");String password=request.getParameter("password"); User user=new User(); user.setUsername(name); user.setPassword(password); session.setAttribute("user",user);response.sendRedirect("filter/loginsuccee.jsp");%><body></body></html>
loginsuccee.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %><%@ page import="com.mr.filter.User"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>使用过滤器身份验证</title></head><body><div align="center"><table width="333" height="285" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <p>您己成功登录</p> <p><br> <a href="backtrack.jsp">返回</a> </p></td> </tr></table></div></body></html>
backtrack.jsp
<%session.invalidate();out.print("<script language='javascript'>window.location.href='../index.jsp';</script>");%>
小结:
过滤器属于自动执行的一种Servlet;
过滤器依然需要在web.xml文件中进行配置;
过滤器的常见功能是可以完成编码过滤及登陆验证