一:过滤器简介
Filter也称之为过滤器,它是Servlet技术中最实用的技术,Web开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。
它主要用于对用户请求进行预处理,也可以对HttpServletResponse进行后处理。使用Filter的完整流程:Filter对用户请求进行预处理,接着将请求交给Servlet进行处理并生成响应,最后Filter再对服务器响应进行后处理。
二:过滤器功能
在HttpServletRequest到达 Servlet 之前,拦截客户的HttpServletRequest 。根据需要检查HttpServletRequest,也可以修改HttpServletRequest 头和数据。
在HttpServletResponse到达客户端之前,拦截HttpServletResponse 。根据需要检查HttpServletResponse,也可以修改HttpServletResponse头和数据。
三:过滤器开发
Filter接口中有一个doFilter方法,当开发人员编写好Filter,并配置对哪个web资源进行拦截后,Web服务器每次在调用web资源的service方法之前,都会先调用一下filter的doFilter方法,因此,在该方法内编写代码可达到如下目的:
调用目标资源之前,让一段代码执行。 是否调用目标资源(即是否让用户访问web资源)。 web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,调用该方法,则web服务器就会调用web资源的service方法,即web资源就会被访问,否则web资源不会被访问。
在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。
web服务器根据Filter在web.xml文件中的注册顺序,决定先调用哪个Filter,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。
Filter的生命周期
public void init(FilterConfig filterConfig) throws ServletException;//初始化
和我们编写的Servlet程序一样,Filter的创建和销毁由WEB服务器负责。 web 应用程序启动时,web 服务器将创建Filter 的实例对象,并调用其init方法,读取web.xml配置,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作(filter对象只会创建一次,init方法也只会执行一次)。开发人员通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain CHAIN) throws IOException, ServletException;//拦截请求
这个方法完成实际的过滤操作。当客户请求访问与过滤器关联的URL的时候,Servlet过滤器将先执行doFilter方法。FilterChain参数用于访问后续过滤器。
public void destroy();//销毁
Filter对象创建后会驻留在内存,当web应用移除或服务器停止时才销毁。在Web容器卸载 Filter 对象之前被调用。该方法在Filter的生命周期中仅执行一次。在这个方法中,可以释放过滤器使用的资源。
FilterConfig接口
用户在配置filter时,可以使用为filter配置一些初始化参数,当web容器实例化Filter对象,调用其init方法时,会把封装了filter初始化参数的filterConfig对象传递进来。因此开发人员在编写filter时,通过filterConfig对象的方法,就可获得以下内容:
STRING getFilterName();//得到filter的名称。
STRING getInitParameter(STRING NAME);//返回在部署描述中指定名称的初始化参数的值。如果不存在返回null.
Enumeration getInitParameterNames();//返回过滤器的所有初始化参数的名字的枚举集合。
public ServletContext getServletContext();//返回Servlet上下文对象的引用。
四:过滤器实例
本实例的作用是使页面支持gzip压缩资源请求(Content-Encoding:gzip)
web.xml配置
代码:
Filter也称之为过滤器,它是Servlet技术中最实用的技术,Web开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。
它主要用于对用户请求进行预处理,也可以对HttpServletResponse进行后处理。使用Filter的完整流程:Filter对用户请求进行预处理,接着将请求交给Servlet进行处理并生成响应,最后Filter再对服务器响应进行后处理。
二:过滤器功能
在HttpServletRequest到达 Servlet 之前,拦截客户的HttpServletRequest 。根据需要检查HttpServletRequest,也可以修改HttpServletRequest 头和数据。
在HttpServletResponse到达客户端之前,拦截HttpServletResponse 。根据需要检查HttpServletResponse,也可以修改HttpServletResponse头和数据。
![](http://img.blog.itpub.net/blog/attachment/201612/5/28624388_14809041935Q2q.jpg?x-oss-process=style/bb)
三:过滤器开发
点击(此处)折叠或打开
- public interface Filter {
-
- /**
- * Called by the web container to indicate to a filter that it is being placed into
- * service. The servlet container calls the init method exactly once after instantiating the
- * filter. The init method must complete successfully before the filter is asked to do any
- * filtering work. <br><br>
-
- * The web container cannot place the filter into service if the init method either<br>
- * 1.Throws a ServletException <br>
- * 2.Does not return within a time period defined by the web container
- */
- public void init(FilterConfig filterConfig) throws ServletException;
-
-
- /**
- * The <code>doFilter</code> method of the Filter is called by the container
- * each time a request/response pair is passed through the chain due
- * to a client request for a resource at the end of the chain. The FilterChain passed in to this
- * method allows the Filter to pass on the request and response to the next entity in the
- * chain.
- * A typical implementation of this method would follow the following pattern:- <br>
- * 1. Examine the request<br>
- * 2. Optionally wrap the request object with a custom implementation to
- * filter content or headers for input filtering <br>
- * 3. Optionally wrap the response object with a custom implementation to
- * filter content or headers for output filtering <br>
- * 4. a) Either invoke the next entity in the chain using the FilterChain object (<code>chain.doFilter()</code>), <br>
- ** 4. b) or not pass on the request/response pair to the next entity in the filter chain to block the request processing<br>
- ** 5. Directly set headers on the response after invocation of the next entity in the filter chain.
- **/
- public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException;
-
- /**
- * Called by the web container to indicate to a filter that it is being taken out of service. This
- * method is only called once all threads within the filter's doFilter method have exited or after
- * a timeout period has passed. After the web container calls this method, it will not call the
- * doFilter method again on this instance of the filter. <br><br>
- *
- * This method gives the filter an opportunity to clean up any resources that are being held (for
- * example, memory, file handles, threads) and make sure that any persistent state is synchronized
- * with the filter's current state in memory.
- */
-
- public void destroy();
-
-
- }
调用目标资源之前,让一段代码执行。 是否调用目标资源(即是否让用户访问web资源)。 web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,调用该方法,则web服务器就会调用web资源的service方法,即web资源就会被访问,否则web资源不会被访问。
在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。
web服务器根据Filter在web.xml文件中的注册顺序,决定先调用哪个Filter,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。
Filter的生命周期
public void init(FilterConfig filterConfig) throws ServletException;//初始化
和我们编写的Servlet程序一样,Filter的创建和销毁由WEB服务器负责。 web 应用程序启动时,web 服务器将创建Filter 的实例对象,并调用其init方法,读取web.xml配置,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作(filter对象只会创建一次,init方法也只会执行一次)。开发人员通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain CHAIN) throws IOException, ServletException;//拦截请求
这个方法完成实际的过滤操作。当客户请求访问与过滤器关联的URL的时候,Servlet过滤器将先执行doFilter方法。FilterChain参数用于访问后续过滤器。
public void destroy();//销毁
Filter对象创建后会驻留在内存,当web应用移除或服务器停止时才销毁。在Web容器卸载 Filter 对象之前被调用。该方法在Filter的生命周期中仅执行一次。在这个方法中,可以释放过滤器使用的资源。
FilterConfig接口
用户在配置filter时,可以使用为filter配置一些初始化参数,当web容器实例化Filter对象,调用其init方法时,会把封装了filter初始化参数的filterConfig对象传递进来。因此开发人员在编写filter时,通过filterConfig对象的方法,就可获得以下内容:
STRING getFilterName();//得到filter的名称。
STRING getInitParameter(STRING NAME);//返回在部署描述中指定名称的初始化参数的值。如果不存在返回null.
Enumeration getInitParameterNames();//返回过滤器的所有初始化参数的名字的枚举集合。
public ServletContext getServletContext();//返回Servlet上下文对象的引用。
四:过滤器实例
本实例的作用是使页面支持gzip压缩资源请求(Content-Encoding:gzip)
web.xml配置
点击(此处)折叠或打开
- <filter>
- <filter-name>GzipJsFilter</filter-name>
- <filter-class>com.gemdale.gmap.manager.web.filter.GzipJsFilter</filter-class>
- <init-param>
- <param-name>headers</param-name>
- <param-value>Content-Encoding=gzip</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>GzipJsFilter</filter-name>
- <url-pattern>*.gzjs</url-pattern>
- </filter-mapping>
点击(此处)折叠或打开
- public class GzipJsFilter implements Filter {
- Map headers = new HashMap();
-
- public void destroy() {
- }
-
- public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
- throws IOException, ServletException {
- if (req instanceof HttpServletRequest) {
- doFilter((HttpServletRequest) req, (HttpServletResponse) res, chain);
- }
- else {
- chain.doFilter(req, res);
- }
- }
-
- public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
- throws IOException, ServletException {
- request.setCharacterEncoding("UTF-8");
- for (Iterator it = headers.entrySet().iterator(); it.hasNext();) {
- Map.Entry entry = (Map.Entry) it.next();
- response.addHeader((String) entry.getKey(), (String) entry.getValue());
- }
- chain.doFilter(request, response);
- }
-
- public void init(FilterConfig config) throws ServletException {
- String headersStr = config.getInitParameter("headers");
- String[] headers = headersStr.split(",");
- for (int i = 0; i < headers.length; i++) {
- String[] temp = headers[i].split("=");
- this.headers.put(temp[0].trim(), temp[1].trim());
- }
- }
- }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28624388/viewspace-2129713/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/28624388/viewspace-2129713/