Web过滤器是什么?
过滤源 (用户请求) ————>过滤规则——->过滤结果
Web过滤器过滤用户请求
过滤器??
定义:过滤器是一个服务器端的组件,它可以截取用户端的请求与响应信息并对这些信息过滤
工作原理?
生命周期?
过滤器分几种类型?
登录认证编码转换实战案例?
过滤器的工作原理:
如果没有过滤器用户可以直接访问web里面的资源
如果有过滤器 (web容器启动的时候自动加载过滤器) 那必须登录喽
原理:用户请求—->过滤器—>过滤器将用户请求发送至web资源
资源响应发送至过滤器——>过滤器将web资源响应给用户
加载web.xml时候 实例化过滤器
初始化———-init()
过滤 ———-doFilter()
销毁—————destory()
init()这是过滤器的初始化方法,web容器创建过滤器实例后
将调用这个方法,这个方法中可以读取web.xml文件中的过滤器参数
doFilter()这个方法完成实际的过滤操作这是过滤器的核心方法
当用户请求访问与过滤器关联的URL时 web容器将先调用doFilter()
FilterChain参数可以调用chain.do.Filter方法将请求传递给下一个
过滤器或者目标资源或者利用转发重定向将请求转发到其他资源
destory() web容器在销毁过滤器实例前调用该方法在这个方法中
可以释放过滤器占用的资源
web.xml的配置
Filter的名字 (过滤器类的完整名字包括报名)
描述信息可以省略或者放在此位置
1.过滤器是否能改变用户请求的web资源??也就是能否改变用户的请求路径?
2.过滤器能否返回数据,能不能直接处理用户请求?? 不能
Web项目中多个过滤器是如何实现?
多个过滤器对应同一个用户路径执行顺序如何?
多个过滤器链
过滤器1 过滤器2
url-pattern == url-pattern 就会生成过滤器链、
过滤器的分类
servlet2.5(request,forward,include,error)
过滤器在实际应用中的场景:
- 1.对用户请求进行统一认证
- 2.编码转换
- 3.对用户发送的数据进行过滤替换
- 4.转换图形格式
5.对响应的内容进行压缩
过滤器链
web.xml<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>com.imooc.filter.FirstFilter</filter-class>
</filter>
<filter>
<filter-name>SecondFilter</filter-name>
<filter-class>com.imooc.filter.SecondFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>SecondFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
FirstFiler.java
public class FirstFilter implements Filter {
public void destroy() {
System.out.println("destory-----FirstFilter");
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
System.out.println("Start---doFilter--FirstFilter");
// chain.doFilter(request, response);
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse response2 = (HttpServletResponse) response;
response2.sendRedirect(req.getContextPath() + "/main.jsp");// 重定向
System.out.println("End----doFilter--FirstFilter");
}
public void init(FilterConfig arg0) throws ServletException {
System.out.println("init");
}
}
SecondFilter.java
public class SecondFilter implements Filter {
public void destroy() {
System.out.println("destory----sendFilter");
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
System.out.println("start----doFilter----sendFilter");
chain.doFilter(request, response);
System.out.println("end----doFilter----sendFilter");
}
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init----sendFilter");
}
}
最后访问index.jsp发现—-
Start—-doFilter—FirstFilter
Start—-doFilter—SecondFilter
End——doFilter—SecondFilter
End——doFilter—FirstFilter