One of the most important new functions of servlet API 2.3 is the ability to define filters for servlet and JSP pages. Filters provide a powerful and standard alternative to non-standard servlet links supported by some early servers.
A filter is a program that runs on the server prior to the servlet or JSP page associated with it. The filter can be attached to one or more servlet or JSP pages, and the request information for accessing these resources can be checked. After that, the filter can be selected as follows:
- Call Resources in the conventional way (that is, call servlet or JSP page ).
- Call resources with modified request information.
- Call the resource, but modify it before sending a response to the client.
- Block this resource call, replace it with another resource, return a specific status code or generate a replacement output.
- Filters only apply to servers compatible with Servlet Specification Version 2.3. If your web application needs to support old-version servers, you cannot use filters.
1. Create a basic Filter
Creating a filter involves the following five steps:
1) create a class to implement the filter interface. This class requires three methods: dofilter, init, and destroy. The dofilter method contains the main filtering code (see step 1). The init method establishes the setting operation, while the destroy method is clear.
2) Put the filtering behavior in the dofilter method. The first parameter of the dofilter method is the servletrequest object. This object provides the filter with full access to the incoming information (including form data, cookies, 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 of the filterchain object. The dofilter method of the filter interface takes a filterchain object as its parameter. When the dofilter method of this object is called, The next related filter is activated. If no other filter is associated with the servlet or JSP page, the servlet or JSP page is activated.
4) register a filter for the servlet and JSP pages. Use the filter and filter-mapping elements in the deployment descriptor file (Web. XML.
5) disable the activator servlet. Prevents users from bypassing the filter settings using the default servlet URL.
1.1 create a class to implement the filter Interface
All filters must implement javax. servlet. filter. This interface contains three methods: dofilter, init, and destroy.
1. Public void dofilter (servletrequset request,
Servletresponse response,
Filterchain chain)
Thows servletexception, ioexception
Every time a filter is called (that is, every time a servlet or JSP page related to this filter is requested), its dofilter method is executed. This method contains most of the filtering logic.
The first parameter is the servletrequest related to the incoming request. For simple filters, most of the filtering logic is based on this object. If an HTTP request is processed and you need to access methods that cannot be obtained in servletrequest, such as getheader or getcookies, You need to construct this object into httpservletrequest.
The second parameter is servletresponse. This parameter is usually ignored except in two cases. First, if you want to completely block access to the relevant servlet or JSP page. Call response. getwriter and send a response directly to the client. Section 7th provides details, and section 8th provides an example. Second, if you want to modify the relevant servlet or JSP page output, you can include the response in an object that collects all the outputs sent to it. Then, after the Serlvet or JSP page is called, the filter can check the output, modify it if appropriate, and then send it to the client. For more information, see section 9th.
The last parameter of dofilter is the filterchain object. This object calls dofilter to activate the next filter related to the servlet or JSP page. If no other related filter exists, call dofilter to activate servlet or JSP itself.
2. Public void Init (filterconfig config)
Thows servletexception
The init method is only executed when the filter is initialized for the first time, not every time the filter is called. For simple filters, You can provide an empty body for this method, but there are two reasons to use init. First, the filterconfig object provides access to the servlet environment and the filter name assigned in the web. xml file. Therefore, the common 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 processing is described in Section 3rd. Secondly, 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 5th.
3. Public void destroy ()
This method is called when a given filter object is used to permanently terminate a server (such as shutting down the server. Most Filters simply provide an empty body for this method. However, they can be used to clear tasks such as closing the file used by the filter or clearing the database connection pool.
1.2 Add the filtering behavior to the dofilter Method
The dofilter method is a key part of most filters. Dofilter is executed every time a filter is called. For most filters, the steps performed by dofilter are based on input information. Therefore, servletrequest provided as the first parameter of dofilter may be used. This object is often constructed as the httpservletrequest type to provide access to more special methods of this class.
1.3 call the dofilter method of the filterchain object.
The dofilter method of the filter interface uses a filterchain object as its third parameter. When the dofilter method of this object is called, The next related filter is activated. This process typically persists until the last filter in the chain. When the last filter calls the dofilter method of its filterchain object, the servlet or page itself is activated.
However, any filter in the chain can interrupt this process by not calling its filterchain dofilter method. In this case, the Serlvet of the JSP page is no longer called, and the filter that interrupts the call process is responsible for providing the output to the client. For more information, see section 7th.
1.4 register filters for appropriate servlets and JSP pages
Version 2.3 of the deployment descriptor file introduces two elements used for the filter: Filter and filter-mapping. The filter element registers a filter object with the system. The filter-mapping element specifies the URL applied to the filter object.
1. filter element
The filter element is located at the front of the deployment descriptor file (Web. XML), before all the filter-mapping, Servlet, or servlet-mapping elements. The filter element has the following six possible child elements:
Icon is an optional element that declares an image file that IDE can use.
Filter-name is a required element, which assigns a selected name to the filter.
Display-Name: This is an optional element, which provides the short name used by IDE.
Description is an optional element that provides ide information and text documents.
Filter-class is a required element. It specifies the fully qualified name of the filter implementation class.
Init-Param is an optional element that defines the initialization parameters that can be read using the getinitparameter method of filterconfig. A single filter element can contain multiple init-Param elements.
Filter-mapping Element
The filter-mapping element is located before the Serlvet element after the filter element in the web. xml file. It contains the following three possible child elements ::
L The required filter-name element must match the name of the filter given when the filter element is declared.
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. However, you cannot provide multiple URL-pattern element items for a single filter-mapping element. If you want the filter to work in multiple modes, you can repeat the entire filter-mapping element.
L servlet-Name: This element provides a name that must match the name of the servlet or JSP page given by the servlet element. You cannot provide multiple servlet-name element items for a single filter-mapping element. If you want the filter to be suitable for multiple servlet names, repeat the filter-mapping element.
Based on the above principle, the project encountered such a problem that the user can only browse the resources under the Resource Directory after logging on, and the addresses of these resources are static addresses, then the filter is used,
Public void dofilter (servletrequest req, servletresponse res,
Filterchain chain) throws ioexception, servletexception {
Httpservletrequest request = (httpservletrequest) req;
Httpservletresponse response = (httpservletresponse) RES;
Httpsession session = request. getsession ();
Servletcontext application = session. getservletcontext ();
If (session. getattribute ("usersession") = NULL)
{
Response. sendredirect ("error/priv_error.jsp ");
Return;
}
Else
{
Chain. dofilter (request, response );
}
}
The following configurations are available in Web. xml:
<Filter>
<Filter-Name> privfilter </filter-Name>
<Filter-class> com. mypriv. Filter. privfilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-Name> privfilter </filter-Name>
<URL-pattern>/resource/* </url-pattern>
</Filter-mapping>
In the filter program, check whether the user session requested in the Resource Directory is empty. If it is empty, the system jumps out;