Perhaps, the most important new feature in the 2.3 version of the Servlet API is to define a filter for the Servlet and JSP pages. The filter provides a powerful and standard alternative to non-standard "servlet links supported by certain early servers.
The filter is a program that is first running on the server before the associated servlet or JSP page. Filters can be attached to one or more servlets or JSP pages and can check for request information that enters these resources. After this, the filter can be selected as follows:
l Call resources in a conventional manner (ie, call the servlet or JSP page).
l Use the modified request information to call resources.
l Call the resource, but modify it before sending response to the client.
l Block the resource call, in order to transfer to other resources, return a specific status code or generate an alternate output.
The filter provides several important benefits.
First, it encapsulates public behavior in a modular or reusable manner. You have 30 different Servervet or JSP pages, need to compress their content to reduce download time? No problem: Construct a compressed filter (see Section 11), then apply it to 30 resources.
Second, it is possible to separate advanced access decisions with the performance code. This is particularly valuable for JSP, which generally wants to focus almost the entire page in performance, rather than concentrating on business logic. For example, I hope to block access from some sites without modifying each page (these pages are subject to access restrictions)? No problem: Create an access restriction filter (see section 8) and apply it to the page you want to restrict access.
Finally, the filter allows you to batch sexual changes to many different resources. You have many existing resources that do you have to keep other remained leaves other than the company's name? No problem: construct a string replacement filter (see Section 10), just use it as appropriate.
But note that filters have functions on servers compatible with the Servlet specification version 2.3. If your web application needs to support the old server, you cannot use a filter.
1. Establish a basic filter
Create a filter involves the following five steps:
1) Establish a class that implements the FILTER interface. This class requires three methods, namely DOFILTER, INIT, and DESTROY. The DOFilter method contains the main filter code (see step 2), the init method establishes the setting operation, and the Destroy method is clear.
2) Put the filtration behavior in the DOFILTER method. The first parameter of the DOFilter method is a servletRequest object. This object provides full access to the incoming information, including form data, cookie, and http request headers. The second parameter is servletResponse, which is usually ignored in a simple filter. The last parameter is Filterchain, as described in the next step, this parameter is used to call the servlet or JSP page.
3) Call the DOFILTER method for the Filterchain object. The DOFILTER method for the FILTER interface takes a Filterchain object as a parameter. When you call the DOFILTER method of this object, activate the next related filter. If another filter is associated with a servlet or JSP page, the servlet or JSP page is activated.
4) Register the filter for the corresponding servlet and JSP page. Use Filter and Filter-Mapping elements in the deployment descriptor file (Web.xml).
5) Disable the activator servlet. Prevent users from bypass the filter settings with the default servlet URL. 1.1 Create a class that implements the Filter interface
All filters must implement javax.servlet.filter. This interface contains three methods, which are DOFILTER, INIT, and DESTROY.
l Public void Dofilter (servletRequset Request,
ServletResponse Response,
FILTERCHAIN chain
Thows ServleTexception, IOException
Whenever a filter is called (ie, the servlet or JSP page associated with this filter is requested), its DOFILTER method is executed. It is this method that contains most of the filtration logic.
The first parameter is a servletRequest associated with the incoming request. For simple filters, most filtering logic is based on this object. If HTTP requests are processed, and you need to access methods such as GetHeader or getCookies, such as getHeader or getCookies, etc., you need to configure this object to configure HttpServletRequest.
The second parameter is servletResponse. This parameter is usually ignored in addition to it in both cases. First, if you want to completely block access to the relevant servlet or JSP page. You can call Response.GetWriter and send a response to the client. Section 7 gives a detailed content, given an example in Section 8. Second, if you want to modify the relevant servlet or JSP page output, you can include a response in an object that collects all sent to its output. The filter can then check the output if you call the Servervet or JSP page, and then send it to the client. See Section 9 for details.
The last parameter of DOFILTER is Filterchain object. This object calls DOFILTER to activate the next filter associated with the Servlet or JSP page. If there is no related filter, the Servlet or JSP itself is activated to the DOFILTER.
l Public void init (FilterConfig Config)
Thows servletexception
The init method is only performed when this filter is first initialized, not per call filter. For simple filters, an air of this method can be provided, but there are two reasons to use init. First, the FilterConfig object provides access to the filter name assigned to the servlet environment and the web.xml file. Therefore, the general method is to use init to store the FilterConfig object in a field so that the DOFILTER method can access the servlet environment or filter name. This process is described in Section 3. Second, the FilterConfig object has a GetInitParameter method that can access the filter initialization parameters allocated in the deployment descriptor file (web.xml). The use of initialization parameters is described in Section 5.
l public void destroy ()
This method is called when a given filter object is permanently terminated. Most filters provide a body for this method, but it can be used to complete clear tasks such as a file or database connection pool such as a shut-off filter.
1.2 Put the filter behavior into the DOFILTER method
The DOFilter method is a key part of most filters. Do Dofilter whenever a filter is called. For most filters, the steps performed by the DOFILTER are based on incoming information. Therefore, it may be necessary to use the servletRequest provided by the first parameter for the DOFILTER. This object is often constructed as an HttpServletRequest type to provide access to more special methods for this class. 1.3 Dofilter method to call the FilterChain object
The DOFILTER method for the FILTER interface takes a Filterchain object as its third parameter. When calling the DOFILTER method of the object, activate the next related filter. This process generally continues until the last filter in the chain. When the last filter calls its FilterChain object's DOFILTER method, activate the servlet or the page itself.
However, any filter in the chain can be interrupted by the DOFILTER method that does not call its Filterchain. In such a case, the Servervet of the JSP page is no longer called, and the filter that interrupts this calling process is responsible for providing the output to the client. See Section 7 for details.
1.4 Register the filter for the appropriate servlet and JSP page
The 2.3 version of the deployment descriptor file introduces two elements for the filter, namely Filter and Filter-Mapping. The Filter element registers a filter object to the system, and the filter-mapping element specifies the URL applied by the filter object.
1.filter element
The Filter element is located before the deployment descriptor file (Web.xml), all Filter-Mapping, servlet, or servlet-mapping element. The Filter element has six possible child elements:
l Icon This is an optional element that declares an image file that IDE can use.
l Filter-name This is an essential element that assigns a selected name to the filter.
l Display-name This is an optional element that gives a short name used by IDE.
l Description This is also an optional element that gives the IDE information, providing a text document.
l Filter-Class This is an essential element that specifies a fully qualified name of the filter.
l INIT-PARAM This is an optional element that defines the initialization parameters that can be read using the GetItParameter method of FilterConfig. A single filter element can contain multiple init-param elements.
Note that filtration is initially introduced in the Server Victor 2.3. Therefore, the web.xml file must use the version 2.3 version of DTD. Here is a simple example:
XML Version = "1.0" encoding = "ISO-8859-1"
?>
DOCTYPE Web-App Public "- // Sun Microsystems, Inc.//dtd Web Application 2.3 // En" "http://java.sun.com/dtd/web-app_2_3.dtd"
>
<
WEB-APP
>
<
Filter
>
<
FILTER-NAME
>
Myfilter
FILTER-NAME
>
<
FILTER-CLASS
>
Mypackage.filterclass
FILTER-CLASS
>
Filter
>
...
->
<
Filter-mapping>
...
FILTER-MAPPING
>
WEB-APP
>
2.Filter-mapping element
Filter-mapping elements Before the serlvet element after the Filvet element in the web.xml file. It contains three possible sub-elements ::
l Filter-name This essential element must match the name of the filter when declared with a Filter element.
l URL-PATTERN This element declares a pattern starting with a slash (/), which specifies the URL of the filter application. URL-pattern or servlet-name must be provided in all Filter-MapPing elements. But you cannot provide multiple url-pattern element items for a single filter-mapping element. If the filter is desired to be used in multiple modes, the entire filter-maping element can be repeated.
l Servlet-name This element gives a name that must match the name of the servlet or JSP page with the servlet element. You cannot provide multiple servlet-name elements for a single filter-mapping element. This filter-mapping element can be repeated if the filter is suitable for multiple servlet names.
Let's take an example:
XML Version
=
"
1.0
"
ENCODING
=
"
ISO-8859-1
"
?>
DOCTYPE Web
-
App public
"
- // Sun Microsystems, Inc.//dtd Web Application 2.3 // EN
"
"
http://java.sun.com/dtd/web-app_2_3.dtd
"
>
<
Web
-
APP
>
<
Filter
>
<
Filter
-
Name
>
Myfilter
Filter
-
Name
>
<
Filter
-
Class
>
Mypackage.filterclass
Filter
-
Class
>
Filter
>
...
->
<
Filter
-
mapping
>
<
Filter
-
Name
>
Myfilter
Filter
-
Name
>
<
URL
-
Pattern
> /
Somedirectory
/
Somepage.jsp
URL
-
Pattern
>
Filter
-
mapping
>
Web
-
APP
>
1.5 Disable Activator Servlet
When you apply a filter for a resource, you can do it by specifying the URL mode or servlet name to apply the filter. If a servlet name is provided, this name must match the name given in the servlet element of Web.xml. This mode must match the mode specified by the element servlet-mapping specified by the element servlet-mapping specified with Web.xml. However, most servers use "activation servlet" for servlet, a default URL: http: // host / webapprew / servlet / servletname. Need to ensure that users do not use this URL to access servlets (this will bypass the filter settings).
For example, if filtering with Filter and Filter-Mapping indicates a servlet called SomeServlet, as follows: <
Filter
>
<
FILTER-NAME
>
Somefilter
FILTER-NAME
>
<
FILTER-CLASS
>
Somepackage.somefilterclass
FILTER-CLASS
>
Filter
>
...
->
<
FILTER-MAPPING
>
<
FILTER-NAME
>
Somefilter
FILTER-NAME
>
<
servlet-name
>
SOMESERVLET
servlet-name
>
FILTER-MAPPING
>
Next, use servlet and servlet-mapping specified URL http: // host / webapppprefix / blah to call SOMESERLVET, as shown below:
<
Filter
>
<
FILTER-NAME
>
Somefilter
FILTER-NAME
>
<
FILTER-CLASS
>
Somepackage.somefilterclass
FILTER-CLASS
>
Filter
>
...
->
<
FILTER-MAPPING
>
<
FILTER-NAME
>
Somefilter
FILTER-NAME
>
<
servlet-name
> / Black
servlet-name
>
FILTER-MAPPING
>
Now, the filter is called when the client uses URL http: // host / webappprefix / blah. Filters are not applied
http: //host/webappprefix/servlet/somepackage.someservletClass.
Despite the dedicated method of server-free server. However, re-mapping the / servlet mode of the web application clock when porting, so that all requests containing this mode are sent to the same servlet. In order to re-map this mode, you should first create a simple servlet, which prints an error message, or redirects the user to the top page. The request to the servlet mode is then sent using the servlet and servlet-mapping element to the servlet. Program Listing 9-1 gives a short example.
Program List 9-1 Web.xml (Redirected Default SERVLET URL)
XML Version = "1.0" encoding = "ISO-8859-1"
?>
DOCTYPE Web-App Public "- // Sun Microsystems, Inc.//dtd Web Application 2.3 // En" "http://java.sun.com/dtd/web-app_2_3.dtd"
>
<
WEB-APP
>
...
->
<
servlet
>
<
servlet-name
>
Error
servlet-name
>
<
Servlet-Class
>
SomePackage.ErrorServlet
Servlet-Class
>
servlet
>
...
->
<
servlet-mapping
>
<
servlet-name
>
Error
servlet-name
>
<
URL-PATTERN
>
/ servlet / *
URL-PATTERN
>
servlet-mapping
>
...
->
WEB-APP
>
2. Sample: Report filter
Hot iron, let's test a simple filter, just call the associated servlet or JSP page, it prints a message to the standard output. In order to complete this task, the corresponding filter must have the following content:
1) A class that implements the Filter interface. This class name is ReportFilter, as shown in Listing 9-2. This class provides a body for the init and destroy methods.
2) Filter behavior in the DOFILTER method. Whenever the Servlet or JSP page associated with this filter is called, the DOFILTER method generates a printout, which lists the URL requesting the host and the call. Because the getRequestURL method is located in httpservletRequest instead of servletRequest, the ServletRequest object is constructed to httpservletRequest type.
3) Call the DOFILTER method of Filterchain. After printing the output report, the filter calls Filterchain's DOFILTER method to activate the servlet or JSP page (if any, call the next filter)
4) Register for the web application home page and the TodaysspecialServlet. First, the Filter element associates the name Reporter with the class beservlets.filters.ReportFilter. The filter is then associated with the home page using the filter-mapping element URL-Patter using /dex.jsp. Finally, the filter-mapping element uses TodayssPecial servlet-name to associate the filter with the TodayssPecialServlet (Name TodayssPeci is declared in the servlet element). See Program List 9-3.
5) Disable the activator servlet. First, create a RedirectorServlet (see Program List 9-6), which redirects all received requests to this web application. Next, all the URLs starting with HTTP: // Host / WebApprefix / servlet / start using the servlet and servlet-mapping elements (see Program Listing 9-3) should also activate the RedirectorServlet.
This filter is called whenever the client requests this web application home page (Program List 9-4) or TodaysspecialServlet (Program List 9-5).
Program List 9-2 ReportFilter.java
Package beeServlets.Filters; import java.io.
*
Import Javax.Servlet.
*
Import javax.servlet.http. *
Import java.util.
*
;
//
For Date Class
/ *
* Simple Filter That Prints A Report On The Standard Output * Each Time An Associated Servlet or JSP Page IS Accessed.
* /
Public Class Reportfilter Implements Filter {Public {PUBLIC
Void
Dofilter (ServletRequest Request, SERVLETRESPONSE RESPONSE, FILTERCHAIN Chain) Throws ServleTexception, IOException {HttpServletRequest Req
=
(HttpservletRequest) Request; System.out.println (Req.getRemotehost ()
"
Tried to Access
"
Req.getRequestURL ()
"
on
"
New
Date ()
"
.
"
CHAIN.DOFILTER (Request, Response);} PUBLIC
Void
INIT (FilterConfig Config) THROWS ServleTexception {} PUBLIC
Void
DESTROY () {}}
Program List 9-3 Web.xml (Extraccha for Report Filters)
Xml Version = "1.0" encoding = "ISO-8859-1"?>
"- // Sun Microsystems, Inc.//dtd Web Application 2.3 // En"
"http://java.sun.com/dtd/web-app_2_3.dtd">
MoreServlets.Filters.Reportfilter
filter-class>
filter>
filter-mapping>
"Todaysspecial".
->
Can be applied to it.
->
MoreServlets.todaysspecialServlet
servlet-class>
servlet>
Named Todaysspecial (I.E., MORSERVLETS.TODAYSSPECIAL).
->
servlet-maping>
servlet-maping>
web-app>
Posted on 2004-07-02 17:07 Khan Read (287) Comments (1) Edit Collection
comment
# RE: Servlet and JSP Filter FILTER
Program List 9-4 Index.jsp