servlet filters 介绍和使用

from : http://servlets.com/soapbox/filters.html

如何利用本文:

1.学习一下用的filter

2.学习写自己的filters



Servlet filters
In case you aren't yet familiar, a filter is an object that can transform arequest or modify a response. Filters are not servlets; they don't actuallycreate a response. They are preprocessors of the request before it reaches aservlet, and/or postprocessors of the response leaving a servlet. As you'llsee later in the examples, a filter can:

  • Intercept a servlet's invocation before the servlet is called
  • Examine a request before a servlet is called
  • Modify the request headers and request data by providing a customizedversion of the request object that wraps the real request
  • Modify the response headers and response data by providing a customizedversion of the response object that wraps the real response
  • Intercept a servlet's invocation after the servlet is called
You can configure a filter to act on a servlet or group of servlets. Zero ormore filters can filter one or more servlets. A filter implementsjavax.servlet.Filter and defines its three methods:
  1. void init(FilterConfig config) throws ServletException:Called before the filter goes into service, and sets the filter'sconfiguration object
  2. void destroy(): Called after the filter has been taken outof service
  3. void doFilter(ServletRequest req, ServletResponse res, FilterChainchain) throws IOException, ServletException: Performs the actualfiltering work
The server calls init(FilterConfig) once to prepare the filterfor service, then calls doFilter() any number of times forrequests specially set up to use the filter. The FilterConfiginterface has methods to retrieve the filter's name, its initparameters, and the active servlet context. The server callsdestroy() to indicate that the filter is being taken out ofservice. The filter lifecycle is now very similar to the servlet lifecycle --a change recently made in the Servlet API 2.3 Public Final Draft #2.Previously the lifecycle involved a setFilterConfig(FilterConfig)method.

In its doFilter() method, each filter receives the currentrequest and response, as well as a FilterChain containing thefilters that still must be processed. In the doFilter() method,a filter may do what it wants with the request and response. (It could gatherdata by calling their methods, or wrap the objects to give them new behavior,as I'll discuss later.) The filter then calls chain.doFilter()to transfer control to the next filter. When that call returns, a filter can,at the end of its own doFilter() method, perform additional workon the response; for instance, it can log information about the response. Ifthe filter wants to halt the request processing and gain full control of theresponse, it can intentionally not call the next filter.


filter lifecycle :

server calls : init(FilterConfig)--> doFilter()-->destroy()

Spot the slowdown
To really understand filters, you have to see them in action. The firstfilter we'll look at is simple but powerful; it records the duration of allrequests. It's modeled loosely after the non-descriptively namedExampleFilter from the Tomcat 4.0 distribution. Here is thecode:

1) Filter codes :

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TimerFilter implements Filter {

  private FilterConfig config = null;

  public void init(FilterConfig config) throws ServletException {
    this.config = config;
  }

  public void destroy() {
    config = null;
  }

  public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {

    long before = System.currentTimeMillis();
    chain.doFilter(request, response);
    long after = System.currentTimeMillis();

    String name = "";
    if (request instanceof HttpServletRequest) {
      name = ((HttpServletRequest)request).getRequestURI();
    }
    config.getServletContext().log(name + ": " + (after - before) + "ms");
  }
}
When the server calls init(), the filter saves a reference to theconfig in its config variable, which is later used in the doFilter() method to retrieve the ServletContext.When the server calls doFilter(), the filter times how long therequest handling takes and logs the time once processing has completed. Thisfilter nicely demonstrates before- and after-request processing. Notice thatthe parameters to the doFilter() method are not HTTP-awareobjects, so to call the HTTP-specific getRequestURI() methodrequires a cast of the request to an HttpServletRequest type.

2) web.xml  配置:

To use this filter, you must declare it in the web.xml deploymentdescriptor using the <filter> tag, as shown below:

<filter>
    <filter-name>timerFilter</filter-name>
    <filter-class>TimerFilter</filter-class>
</filter>
This notifies the server that a filter named timerFilter isimplemented in the TimerFilter class. You can apply a registeredfilter to certain URL patterns or servlet names using the <filter-mapping> tag:
<filter-mapping>
    <filter-name>timerFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
This configures the filter to operate on all requests to the web application(static or dynamic), just what we want for our timing filter. If you connectto a simple page, the log output might look like this:
2001-05-25 00:14:11 /timer/index.html: 10ms
In Tomcat 4.0 beta5, you'll find the log file under server_root/logs/.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值