过滤器Filter
最后更新于:2022-04-01 09:42:20
# 过滤器Filter
### 基本概述
Java中的Filter 并不是一个标准的Servlet ,它不能处理用户请求,也不能对客户端生成响应。 主要用于对HttpServletRequest 进行预处理,也可以对HttpServletResponse 进行后处理,是个典型的处理链。
参考文档:[http://tomcat.apache.org/tomcat-5.5-doc/servletapi/index.html](http://tomcat.apache.org/tomcat-5.5-doc/servletapi/index.html)
参考博客:[http://blog.csdn.net/sd0902/article/details/8395641](http://blog.csdn.net/sd0902/article/details/8395641)
### 开发过滤器的步骤
#### 1、创建
继承HttpServlet 同时实现Filter接口
默认filter不生效,需要配置.
~~~
<!-- 配置的一个filter -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.pc.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern> /*表示对该WEB的所有网页都过滤
</filter-mapping>
~~~
#### 2、在filter的方法中添加业务逻辑
~~~
package com.pc.filter;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.pc.domain.User;
public class MyFilter1 extends HttpServlet implements Filter {
public void doGet(HttpServletRequest request, HttpServletResponse response)hrows ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
System.out.print("myfilter1...");
//获取session
HttpServletRequest httpServletRequest=(HttpServletRequest)request;
//看看请求的资源是什么
String uri=httpServletRequest.getRequestURI();
if(uri.startsWith("/UsersManager3/imgs")||uri.startsWith("/UsersManager3/Login")){
// 该过滤器放行,进入下一个过滤器
chain.doFilter(request, response);
}else{
HttpSession session=httpServletRequest.getSession();
User user=(User) session.getAttribute("loginuser");
if(user!=null){
//该用户合法,放行
chain.doFilter(request, response);
}else{
request.setAttribute("err", "请好好登陆");
httpServletRequest.getRequestDispatcher("/LoginServlet")
.forward(request, response);
}
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
~~~
### 过滤器链
过滤器链的概念很容易理解,就是在配置过滤器时,多个过滤器加载进内存中时,当使用过滤器之后调用chain.doFilter(request, response);WEB服务器会按配置顺序决定下一个调用的过滤器是什么。这就可以视为过滤器链。
----------参考《韩顺平.细说Servlet》