文件名称:
Java web Filter 简介和工作原理
开发工具:
文件大小: 495kb
下载次数: 0
上传时间: 2019-03-17
详细说明:NULL
博文链接:https://419443161-qq-com.iteye.com/blog/542335O Sun Microsystems and Prentice Hall. Personal use only; do not redistribute without permission.
436
Chapter 9 Servlet and jsP Filters
Second, it lets you separate high-level access decisions from presentation code
This is particularly valuable with JSP, where you usually want to keep the page almost
entirely focused on presentation, not business logic. For example, do you want to
block access from certain sites without modifying the individual pages to which these
access restrictions apply? No probleIn: create an access restriction filter(Section 9.8
and apply it to as many or few pages as you like
Finally, filters let you apply wholesale changes to many different resources. Do
ou have a bunch of existing resources that should remain unchanged except that the
company name should be changed? No problem: make a string replacement filter
(Section 9.10)and apply it wherever appropriate
Remember, however, that filters work only in servers that are compliant with ver-
sion 2.3 of the servlet specification. If your Web application needs to support older
servers, you cannot use filters
Core Warning
Filters fail in servers that are compliant only with version 2. 2 or earlier
versions of the servlet specification
9.1 Creating Basic Filters
Creating a filter involves five basic steps
1. Create a class that implements the Filter interface. Your class
will need three methods: do, init, and destroy. The
doFilter method contains the main filtering code(see Step 2), the
init method performs setup operations, and the destroy method
does cleanup
2. Put the filtering behavior in the doFilter mcthod. The first
argunent to the doFilter Inethod is a ServletRequest object
This object gives your filter full access to the incoming information
includingformdatacookiesandhttprequestheadersThesecond
argument is a ServletResponse; it is mostly ignored in simple fil-
ters. The final argument is a Filterchain; it is used to invoke the
servlet or jSP page as described in the next step
3. Call the doFilter method of the Filterchain object The
doFllt
thod of the filter interface takes a filtercha
object as one of its arguments. When you call the doFilter method
Bookhomepagehttp://www.moreservlets.com
ServletandjSptrainingcourseshttp://courses.moreservlets.com/
o Sun Microsystems and Prentice Hall. Personal use only; do not redistribute without permission
9.1 Creating Basic Filters437
of that object the next
ted filter is invoked. If no other filter is
associated with the servlet or jSP page, then the servlet or page itself
Is Inv
4. Register the filter with the appropriate servlets and JSP pages
Jse the filter and filter-mapping elements in the deployment
descriptor (web. xml)
5. Disable the invoker servlet. Prevent users from bypassing filter set
tings by using default servlet urls
Details follow
Create a Class That Implements
the filter interface
All filters must implement javax. servlet Filter. This interface comprises
three mcthods: doFilter, init, and destroy
public void doFiltcr(ScrvlctRcqucst rcqucst,
ServletResponse response
Filter Chain chain
throws ScrvlctExccption, IOExccption
The doFilter method is executed each time a filter is invoked (i.e, once for
each request for a servlet or jSp page with which the filter is associated). It is
this method that contains the bulk of the filtering logic
The first argument is the ServletRequest associated with the incoming
request. For simple filters, most of your filter logic is based on this object. Cast
theobjecttohttpservletrequeStifyouaredealingwithhttprequests
and you need access to methods such as getlleader or getCookies that are
unavailable in ServletRequest
The second arguinent is the ServletResponse. You often ignore this
argument, but there are two cases when you use it first if you want to com
pletely block access to the associated servlet or JSp page, you can call
response. getWriter and send a response directly to the client. Section
9. 7 gives details; Section 9.8 gives an example. Second, if you want to modify
the output of the associated servlet or isp page, you can wrap the response
inside an object that collects all output sent to it. Then, after the servlet or
JSP page is invoked, the filter can examine the output, modify it if appropri-
ate. and then send it to the client. See section 9.9 for details
Bookhomepagehttp://www.moreservlets.com
Servletandjsptrainingcourseshttp://coursesmoreservlets.com
O Sun Microsystems and Prentice Hall. Personal use only; do not redistribute without permission.
438
Chapter 9 Servlet and jsP Filters
The final argument to doFilter is a FilterChain object. You call
doF ilter on this object to invoke the next filter that is associated with the
servlet or SP page. In no other filters are in effect, then the call to doFilter
invokes the servlet or JSP page itself
public void init( FilterConfig config
throws ServletException
The init method is executed only when the filter is first initialized. It is not
executed each time the filter is invoked. For simple filters you can provide an
empty body to this method but there are two common reasons for using init
F'irst, the Filter Config object provides access to the servlet context and to
the name of the filter that is assigned in the web, xml file. So it is common to
use init to store the Filterconf ig object in a field so that the dofilter
method can access the servlet context or the filter name. This process is
described in Section 9.3. Second, the FilterConfig object has a getInit-
Parameter method that lets you access filler iniTialization parameters that are
assigned in the deployment descriptor(web. xm/). Use of initialization parame-
ters is described in Section 9.5
public void destroyo
This method is called when a server is permanently finished with a given filter
object(e. g, when the server is being shut down). Most filters simply provide an
empty body for this method, but it can be used for cleanup tasks like closing
files or database connection pools that are used by the filter
Put the Filtering behavior
in the doFilter Method
The doFilter method is the key part of most filters. Each time a filter is invoked
doFilter is executed. With most filters, the steps that doFilter performs are
based on the incoming information. So, you will probably make use of the Servlet
Request that is supplied as the first argument to doFilter. This object is fre-
quently typecast to Ht=pServletRequest to provide access to the more
specialized methods of that class
Call the doFilter method
of the filter Chain object
The doFilter method of the Filter interface takes a Filterchain object as its
third argument When you call the doF ilter method of that object, the next associ
ated filter is invoked. This process normally continues until the last filter in the chain
Bookhomepagehttp://www.moreservlets.com
ServletandjSptrainingcourseshttp://courses.moreservlets.com/
o Sun Microsystems and Prentice Hall. Personal use only; do not redistribute without permission
9.1 Creating Basic Filters
439
is invoked. When the final filter calls the dofilter method of its Filterchain
object, the servlet or page itself is invoked.
However, any filter in the chain can interrupt the process by omitting the call to
the dofilter method of its Filter Chain. In such a case, the servlet of sp page
is never invoked and the filter is responsible for providing output to the client. For
details, see Section 9. 7(Blocking the Response)
Register the Filter with the
Appropriate Servlets and JSP Pages
Version 2.3 of the deployment descriptor introduced two elements for use with fil
ters: filter and filter-mapping. The filter element registers a filtering
object with the system. The filter-mapping element specifies the URLs to which
the filtering object applies
The filter element
The filter element goes near the top of deployment descriptor (web. xml), before
any filter-mapping, servlet, or servlet-mapping elements(For more
information on the use of the deployment descriptor, see Chapters 4 and 5. F'or
details on the required ordering of elements within the deployment descriptor, see
Section 5. 2. The filter element contains six possible subelements
icon. This is an optional element that declares an image file that an
IDE can use
filter-name. This is a required element that assigns a name of your
choosing to the filter
display-name. This is an optional element that provides a short
name for use by ides
description. This is another optional element that gives
information for IDEs. It provides textual documentation
filter-class. This is a required element that specifies the fully
qualified name of the filter implementation class
init-param. This is an optional element that defines initialization
parameters that can be read with the getInitParameter method of
Filterconfig. A single filter element can contain multiple init
param elements
Remember that filters wero first introduced in version 2. 3 of the servlet specifi
cation. So, your web. xml file must use version 2.3 of the DTD. Here is a simple
Bookhomepagehttp://www.moreservlets.com
ServletandjsPtrainingcourseshttp://courses.moreservlets.com
O Sun Microsystems and Prentice Hall. Personal use only; do not redistribute without permission.
440
Chapter 9 Servlet and jsP Filters
< DOCTVPE web-app PUBLIC
// Sun Microsystems, Inc.//DTD Web Application 2. 3//EN
http://3ava.suncom/dtd/web-app23.ata">
eb-ap
<£1七ex
MyFilter
my Package. Filterclass
fi-ter-mapping>.
< DOCTYPE Web-app PUBLIC
// Sun Microsys teIs, Inc.//DTD Web Application 2.3//EN
http://iava.suncom/atd/web-app_2_3.ata">
<2⊥ter>
MyFilter
myPackage. Filterclass
Bookhomepagehttp://www.moreservlets.com
ServletandjSptrainingcourseshttp://courses.moreservlets.com/
o Sun Microsystems and Prentice Hall. Personal use only; do not redistribute without permission
9.1 Creating Basic Filters44
MyFilter/someDirectory/Some Page.]sp
/王i1t
Ing>
Disable the Invoker Servlet
When you apply filters to resources, you do so by specifying the URL pattern or serv-
let name to which the filters apply. If you supply a servlet name, that name must
match a name given in the servlet element ofweb. xml. If you use a URL pattern
that applies to a servlet the pattern must match a pattern that you specified with the
servlet-mapping web xml element(see Section 5.3, Assigning Names and Cus-
tom URLS"). However, most servers use an"invoker servlet" that provides a default
Urlforservletshttp://host/webappprefix/serulet/seruletnamE.Youneedtomake
sure that users dont access servlets with this URL, thus bypassing the filter settings
For example, suppose that you use filter and filter-mapping to say that
the filter named SomeFilter applies to the servlet named Some Servlet,as
below
SomeFilter
some Package. SomeFilterClass
Somef'ilter
servlet
王i1ter- mapping>
Nextyouuseservletandservlet-mappingtostipulatethattheurlhttp://host/
webApPrefi/Blah should invoke Some Servlet, as below
servlet-name>Some Servlet
somePackage. SomeServletclass
SomeServlet
/Blah
Error
some Package. Errorservlet
Error
cl-pattern>/servlet/*
9.2 Example: A Reporting Filter
Just to warm up, lets try a simple filter that merely prints a message to standard out
out whenever the associated servlet or jSP page is invoked. To accomplish this task,
the filter has the following capabilities
1. A class that implements the Filter interface. This class is called
ReportFilter and is shown in Listing 9. 2. The class provides empty
bodies for the init and destroy methods
Bookhomepagehttp://www.moreservlets.com
ServletandjSptrainingcourseshttp://courses.moreservlets.com/
o Sun Microsystems and Prentice Hall. Personal use only; do not redistribute without permission
9.2 Example: A Reporting Filter
443
2. Filtering behavior in the doFilter method. each time a servlet
or jSP page associated with this filter is invoked, the doFilter
method generates a printout that lists the requesting host and the
HttpservletrequesT, nlot Servletrequest, I cast thein
URL that was invoked. Since the getRequestURI method is in
Servletrequestobjecttohttpservletrequest.
3. A call to the doFilter method of the Filterchain After print-
ing the report, the filter calls the doFilter nethod of the Filter
Chain to invoke the servlet or ]Sp page(or the next filter in the chain
if there was one.
4. Registration with the Web application home page and the
servlet that displays the daily special. First, the filter element
associates the name Reporter with the class moreservlets
filters. ReportFilter. Then, the filter-mapping element
uses aurl-pattern of /index. jsp to associate the filter with the
Finally, the filte
clement uses a servlet
name of Todays Special to associate the filter with the daily special
servlet (the name Todays special is declared in the servlet ele
sting 9. 3
5. Disablement of the invoker servlet First. i created a
RedirectorServlet(Listing 9.6)that redirects all requests that it
receives to the Web application home page. Next, I used the servlet
and servlet-mapping elements(Listing 9. 3)to specily that all
Urlsthatbeginwithhttp://host/ebappprefir/serilet/shouldinvoke
the redirectorServlet
Given these sellings, the filter is invoked each time a client requests the Web
application home page(I isting 9.4, Figure 9-1)or the daily special servlet( isting
9.5, Figure 9-2)
Listing 9.2 ReportFilter java
package moreservlets filters
Import java.10
import javax. servlet. x
importjavax.servlethttp*
import java.util. *i , For Date class
imple ilter that prints a report on the standard output
each time an associated servlet or jsp page is accessed
Bookhomepagehttp://www.moreservlets.com
Servletandjsptrainingcourseshttp://coursesmoreservlets.com
(系统自动生成,下载前可以参看下载内容)
下载文件列表
相关说明
- 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
- 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度。
- 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
- 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
- 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
- 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.