JSP -Filter

来源:互联网 发布:小李子颜值 知乎 编辑:程序博客网 时间:2024/06/06 12:47

什么是过滤器:

过滤器是一个服务器端的组件,它可以截取客户端的请求和服务端的响应信息,并对这些信息进行过滤。

过滤器工作原理:

编写第一个Filter实例:

Filter是实现的Filter接口 导入的是javax.servlet 包下的资源

一:创建一个类实现Filter接口,重写其中的doFilter().init().destory()方法

/* *  导入的jar包是javax.servlet.*; *  step:1----- *  在web.xml文件中配置,实例化一个Filter实例*/public class firstFilter implements Filter{   //step:4public void destroy() {// TODO Auto-generated method stubSystem.out.println("服务器关闭,销毁Filter  执行destory方法");}    //step:3public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {System.out.println("开始运行doFilter--");arg2.doFilter(arg0, arg1);System.out.println("结束运行doFilter--");}   // step:2public void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stubSystem.out.println("Filter初始化方法:init()");}}


二::在web.xml文件中配置;



 <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <filter>      <filter-name>Filter</filter-name>       <filter-class>FirstFilter.firstFilter</filter-class>  </filter>    <filter-mapping>  <filter-name>Filter</filter-name>  <url-pattern>/index.jsp</url-pattern>  </filter-mapping></web-app>
其中需要注意的是:

<url-pattern>中网址前面有一根 /    当用户请求index.jsp的时候就会触发该过滤器然后再发送给web资源

<filter-name>是可以随你自己指定的过滤器名字 

<filter-class>为filter的全名(包名加类名)

三:就是编写index.jsp文件了  :

我的是很简单的一句话

  <body>
    hello.firstFilter <br>
  </body>


看看Filter的实现过程:

step1:web.xml文件 实例化Filter

step2:执行过滤器中的init()方法读取web.xml文件中配置参数实现该过滤器的初始化 

以上两步在服务器启动时开始执行  成功执行

信息: Deploying web application directory E:\apache-tomcat-7.0.42\webapps\FilterFilter初始化方法:init()五月 04, 2017 8:13:58 上午 org.apache.catalina.startup.HostConfig deployDirectory

当服务器成功启动时  

step3:执行doFilter()方法这是过滤器实际的过滤操作   

step4:服务器关闭的时候就会执行destory方法

当客户访问indexjsp页面时触发过滤器执行过滤器的doFilter()方法  过滤后使用doFilter方法中FilterChain.doFilter()把请求转发给下一个过滤器或者web资源或者通过请求或转发发送给其他资源 ,资源响应后发送给客户的途中也会被过滤器拦截,过滤器处理响应后再发送给客户端(过滤器工作原理) 也就是过滤器会执行两次(这句话我总感觉有问题)    

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

————————————————————————————————————————————————————————--—————————-

滤器链:

就是对一个网页进行多个过滤

过滤器链的工作原理:


当用户发送请求请求Web资源时,过滤器1会首先获取用户的请求,对请求进行过滤,然后执行FilterChain.doFilter()将请求发送给过滤器2,过滤器2在过滤了用户请求之后执行FilterChain.doFilter()方法请求实际的Web资源,Web资源的响应将首先被过滤器2获取,在过滤器2对响应进行过滤之后将响应传递给过滤器1,在过滤器1过滤之后才将响应发送给用户

实现一个过滤链 :

package 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;/* *  导入的jar包是javax.servlet.*; *  step:1----- *  在web.xml文件中配置,实例化一个Filter实例*/public class secondFilter implements Filter{   //step:4public void destroy() {// TODO Auto-generated method stubSystem.out.println("服务器关闭,销毁Filter2  执行destory方法");}    //step:3public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {System.out.println("开始运行doFilter2--");arg2.doFilter(arg0, arg1);System.out.println("结束运行doFilter2--");}   // step:2public void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stubSystem.out.println("Filter2初始化方法:init()");}}

xml文件配置:

其中只有url配置一样才能组成一个过滤链

<filter>      <filter-name>Filter</filter-name>       <filter-class>FirstFilter.firstFilter</filter-class>  </filter>    <filter-mapping>  <filter-name>Filter</filter-name>  <url-pattern>/index.jsp</url-pattern>  </filter-mapping>      <filter>        <filter-name>sFilter</filter-name>        <filter-class>FirstFilter.secondFilter</filter-class>    </filter>        <filter-mapping>  <filter-name>sFilter</filter-name>  <url-pattern>/index.jsp</url-pattern>  </filter-mapping></web-app>


执行结果:




我发现filter执行init()方法时  先执行的第二个过滤器     destory时也是

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------=----------------------------------------------------------

=====================----=-=-=-=-=--=-==--=============================================================================================-

过滤器的分类:

所谓过滤器的分类就是指定义的过滤器对哪一种类型的请求进行过滤,具体体现在在web.xml文件中声明一个过滤器时,声明的dispatcher标签的值,具体的取值及用法可以参考下图(图片转自慕课网)。



1、REQUEST

这个类型是最常用的,也是dispatcher标签的默认值,表示用户直接请求一个Web资源时触发过滤器。之前介绍的几个过滤器实例都是REQUEST类型的,当用户直接请求index.jsp页面时触发了相应的过滤器
例子就是firstFliter类,配置文件 没变默认的dispatcher为request 

public class firstFilter implements Filter{   //step:4public void destroy() {// TODO Auto-generated method stubSystem.out.println("服务器关闭,销毁Filter  执行destory方法");}    //step:3public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {System.out.println("First Filter------doFilter start");          HttpServletResponse response = (HttpServletResponse) arg1;                  response.sendRedirect("index.jsp");        arg2.doFilter(arg0, arg1);          System.out.println("First Filter------doFilter end");  }   // step:2public void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stubSystem.out.println("Filter初始化方法:init()");}}


当使用重定向时由于属于两次不同的请求,所以服务器无限循环该过滤器()直到浏览器提示重定向过多  当然不再重定向到index.jsp就不会出现这个错误

如果将重定向改为服务器内部转发,会有什么结果呢?再次修改FirstFilter的doFilter()方法,使用HttpServletRequest..getRequestDispatcher("index.jsp").forward(arg0, arg1)方法将请求转发给index.jsp。

2、FORWARD

服务器内部转发:特点是页面跳转不会改变url 相当于同一次请求,在服务器内部跳转  也就是说相对而言更消耗资源
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {System.out.println("First Filter------doFilter start");           HttpServletResponse response = (HttpServletResponse) arg1;          HttpServletRequest request =(HttpServletRequest) arg0;       request.getRequestDispatcher("hello.jsp").forward(request,response);              arg2.doFilter(arg0, arg1);          System.out.println("First Filter------doFilter end");  }

配置文件:
 </welcome-file-list>  <filter>      <filter-name>Filter</filter-name>       <filter-class>FirstFilter.firstFilter</filter-class>         </filter>    <filter-mapping>   <filter-name>Filter</filter-name>   <url-pattern>/index.jsp</url-pattern>    <dispatcher>FORWARD</dispatcher>    </filter-mapping>    <filter-mapping>   <filter-name>Filter</filter-name>   <url-pattern>/main.jsp</url-pattern>    <dispatcher>FORWARD</dispatcher>    </filter-mapping>

3、INCLUDE

和forward差不多所以这里就不说了

4、ERROR


当我们输入不存在的页面url时 浏览器会提示我们404错误  如何把错误信息变得更容易处理和美观就需要使用ERROR dispatcher了

如何实现:
①:创建一个过滤器

ublic class errorfilter implements Filter {public void destroy() {// TODO Auto-generated method stub}public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {// TODO Auto-generated method stub
system.out.print("有错误信息");                        arg2.doFilter(arg0, arg1);}public void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stub}

②:web.xml文件配置:
 <error-page>    <error-code>404</error-code>    <location>/error.jsp</location>  </error-page>    <filter>        <filter-name>error</filter-name>        <filter-class>Filterfenlei.errorfilter</filter-class>    </filter>     <filter-mapping>   <filter-name>error</filter-name>   <url-pattern>/error.jsp</url-pattern>    <dispatcher>ERROR</dispatcher>    </filter-mapping> </web-app>
③:创建一个error.jsp 

其中<error-page>标签是获得浏览器抛出的错误,如果是404我们就跳转到error.jsp (有斜杠)  然后Filter就会拦截该页面进行处理然后再给web资源处理

我试了一下如果在error Filter 中使用页面跳转的话会发生错误

public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {// TODO Auto-generated method stub       System.out.println("有错误信息");       HttpServletResponse response = (HttpServletResponse) arg1;       response.sendRedirect("error.jsp");            arg2.doFilter(arg0, arg1);}

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)at java.lang.Thread.run(Thread.java:745)五月 04, 2017 5:04:59 下午 org.apache.catalina.core.StandardHostValve custom严重: Exception Processing ErrorPage[errorCode=404, location=/error.jsp]org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.IllegalStateException: Cannot create a session after the response has been committed


0 0
原创粉丝点击