Servlet and JSP Filter Filter

xiaoxiao2021-03-06  41

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)

"- // Sun Microsystems, Inc.//dtd Web Application 2.3 // En"

"http://java.sun.com/dtd/web-app_2_3.dtd">

Reporter

MoreServlets.Filters.Reportfilter

Reporter

/index.jsp

"Todaysspecial".

->

Reporter

Todaysspecial

Can be applied to it.

->

Todaysspecial

MoreServlets.todaysspecialServlet

Named Todaysspecial (I.E., MORSERVLETS.TODAYSSPECIAL).

->

Todaysspecial

/ todaysspecial

redirector

/ servlet / *

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 filters 'R' US </ Title> <link Rel = Stylesheet href = "filter-styles.css" type = "text / css"> </ head> <body> <center> <table border = 5> <tr> <TH class = "title"> filters 'r' US </ TABLE> <P> <Table> <TR> <TH> <img src = "images / air-filter.jpg" alt = "air filter"> <TH> <img src = "images / coffee-filter .gif "alt =" coffee filter "> <TH> <img src =" images / pump-filter.jpg "alt =" pump filter "> </ tr> </ table> <h3> We Specialize in the Following: </ H3> <ul> Coffee filters <li> pump filters <li> camera lens filters <li> image filter file adobe photoshop <li> Web Content Filters <li> Kalman Filters <li> Servlet and JSP Filters </ ul> Check Out <a href="toDaysspecial"> Today's Special </a. </ Center> </ body> </ html> program list 9-5 TodaysspecialServlet.javaPort Java; Import Java. IO. *; import javax.servlet. *; import javax.servlet.http. *; / ** Sample Servlet Used to test the simple filters. * / public class TodaysSpecialServlet extends HttpServlet {private String title, picture; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {updateSpecials (); response.setContentType ( "text / html"); PrintWriter out = response.getWriter ();</p> <p>String doctype = "<! Doctype html public /" - // w3c // DTD HTML 4.0 " " transitional /// "> / n"; out.println (DOCTYPE "<HTML> / N" "< Head> <title> Today's Special </ title> </ head> / n " " <body bgcolor = / "white /"> / n " " <center> / n " " <h1> Today's Special: " Title "S! </ H1> / n" "<img src = /" image / " picture " / "/ n" "alt = /" " Title " / "> / n" "<br Clear=/"all/"> / N" "Special DEAL: for only twice the price, you can / n" "<i> Buy One, get one free! </ I> ./ n " " </ Body> </ html> ");} // rotate among the Three Available filter images. Private void updatespecials () {Double Num = Math.random (); if (Num <0.333) {Title =" Air filter "; Picture =" air-filter.jpg ";} else if (Num <0.666) {title =" coffee filter "; Picture =" Coffee-filter.gif ";} else {title =" pump filter "; Picture = "pump-filter.jpg";}}} program list 9-6 RedirectorServlet.javaPackage Import java.io. *; import javax.servlet. *; import javax.servlet.http. *;</p> <p>. / ** Servlet that simply redirects users to the * Web application home page Registered with the * default servlet URL to prevent clients from * using http: // host / webAppPrefix / servlet / ServletName * to bypass filters or security settings that * are . associated with custom URLs * / public class RedirectorServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.sendRedirect (request.getContextPath ());} public void doPost (HttpServletRequest request, HttpServletResponse response) THROWS servletexception, IOException {doget (request, response);}} 3. The ReportFilter of the previous section of the previous section of the Servlet Environment will print a report on the standard output as long as the specified servlet or JSP page is called. When you run a server on your desktop system, you usually use a window that displays a standard output. During the development process, the report on the standard output is very useful. But in the deployment process, it is impossible to access this window. Therefore, a natural improvement is to write the report to the servlet log file to the standard output. The Servlet API provides two log methods: a simple string and another string and a throwable. Both methods can be used from the GenericServlet or ServletContext class. For the exact location of the log files used in these two methods, check the help documentation of the relevant server. The problem is that the DOFilter method is executed before the Servervet or JSP page related to it. Therefore, you cannot access the instance of the servlet, so that the log method inherited from genericServlet cannot be called. In addition, the API does not have an easy way to access ServletContext from the Dofilter method. You can access the method of servletContext and the only class associated with the filter is FilterConfig, and the method of accessing servletContext is GetServletContext. The FilterConfig object is transmitted to the init method, but it does not automatically store some location available to the DOFILTER. Therefore, you must store Filterconfig yourself. A field of FilterConfig types can be created, then reloaded init, assign it to this field. Because only the FilterConfig objects generally use the servletContext and filter names, the servletContext and the name can be stored in the field.</p> <p>Physiognomy an example: public class SomeFilter implements Filter {protected FilterConfig config; private ServletContext context; private String filterName; public void init (FilterConfig config) throws ServletException {this.config = config; // In case it is needed by subclass. Context = config.getServletContext (); FilterName = config.getfilterName ();} // DOFILTER AND DESTROY METHODS ...} 4. Example: Log Record Filter Let's update ReportFilter (Program Listing 9-2) so that the message enters the log file instead of the standard output. In order to complete this task, the filter should have the following: 1) Implement a class of the Filter interface. This class name is logfilter, as shown in Listing 9-7. This class's init method stores FilterConfig, ServletContext, and filter names in the fields of filters. It provides an air for the Destory method. 2) Filter behavior in the DOFILTER method. There are two points between this behavior and the REPORTFILTER behavior: reports in the log file rather than standard outputs, the report includes the name of the filter. 3) Call the DOFILTER method of Filterchain. After printing a report, this filter calls the next filter in the DOFILTER method of Filterchain (if there is no more filter, activate the servlet or JSP page). 4) Register all URLs. First, the Filter element will be associated with the name logfilter with the class beservlets.filters.logfilter. Next, the filter-patter used by the Filter-Mapping element uses the value / * associates this filter with all the URLs in the web application. Referring 9-8.5) Disable activation servlet. This operation has been introduced in Section 2, and it will not be repeated here. When this web application is deployed on an external server and attached to the logging filter, the client will generate an item in the log file, such as "audits.irs.gov Tired to Acces HTTP: //www.filtersrus.com/filters/index.jsp On Fri Oct 26 15:16:15 Edt 2001. (Reported by Logger.) ".</p> <p>Program List 9-7 Logfilter.javaPackage MoreServlets.Filters; Import Java.io. *; Import Javax.Servlet. *; Import Javax.Servlet.http. *; Import Java.util. *; // for Date Class / ** Simple filter that prints a report in the log file * whenever the associated servlets or JSP pages * are accessed * / public class LogFilter implements filter {protected FilterConfig config;. private ServletContext context; private String filterName; public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {HttpServletRequest req = (HttpServletRequest) request; context.log (req.getRemoteHost () "tried to access" req.getRequestURL () "on" new Date () " " " (Reported by " filter " ")"); chain.dofilter (Request, response);} public void init (filterconfig config) throws servletexception {this.config = config; // in c ASE it is needed by subclass. context = config.getServletContext (); filtername = config.getfiltername (); public void design {}} program list 9-8 Web.xml (Extract for logging filter) < 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> <! for logfilter. -> <filter> <filter -Name> Logger </ filter-name> <filter-class> moreservlets.filters.logfilter </ filter-class></p> <p></ filter> - ... -> <filter-mapping> <filter-name> Logger </ filter-name> <Filter-Name> < URL-PATTERN> / * </ url-pattern> </ filter-maping> <! - ... -> </ web-app> 5. The initialization parameters of the filter can be customized by providing initialization parameters for the servlet and JSP pages. The reason why this feature is swimming is that there are three groups of different personnel may want to customize the Servlet or JSP page, and these three groups are: 1) Developers - they customize the corresponding behavior by changing the code of the Server or JSP page. 2) End users - they customize the corresponding behavior by entering values ​​in the HTML form. 3) Deployment person - this is a group of people who provide initialization parameters. This group of people are those who get existing web applications (or individual servlets or JSP pages) and deploy them in a custom environment environment. They don't necessarily have developers, so they expect them to modify the servlet and JSP code is unrealistic. However, because the filter is performed before they have an additional servlet or JSP page, end users generally cannot customize the behavior of the filter, which is still useful. The behavior of the custom filter is done with the following steps: 1) Define the initialization parameters. Using Filter's init-param child elements in Web.xml and PARAM-NAM and PARAM-VALUE sub-elements, as shown below. <filter> <filter-name> Somefilter </ filter-name> <filter-class> SomePackage.somefilterclass </ filter-class> <init-param> <param-name> param1 </ param-name> <param-value > Value1 </ param-value> </ init-param> <init-param> <param-name> param2 </ param-name> <param-value> value2 </ param-value> </ init-param> < / filter> 2) Read initialization parameters. Call the GetItParameter method for FilterConfig from the INTI method of the filter. As follows. Public void init (FilterConfig config) throws servletexception {string varing value = config.getinitParameter ("param1"); string var 2 = config.getinitParameter ("param2"); ...} 3) Analyze initialization parameters. Just like the initialization parameters of Servlet and JSP, each filter is initialized in the String type. Therefore, if other types of values ​​must be converted. For example, use Integer.Parseint to convert String "7" to INT 7.</p> <p>At the time of analysis, don't forget to check the missing and bad data. The lack of initialization parameters will cause NULL from GetInitParameter. Even if these parameters are present, it is also possible to consider the possibility that deployers are formatted correctly. For example, when converting the value of the String type is the value of the INT type, the Integer.Parseint call should be encapsulated in TRY / CATCH, and this block captures NumberFormATexception. This approach has completely handled NULL and formatting incorrect values. 6. Example: Access When the Logfilter of Section 4 of the Filter, a certain item is printed in the log file whenever the associated servlet or JSP page is accessed. If you want to modify it, you only pay only an access to the unusual moment. Because "unusual" is depending on the specific situation, servlet should provide the default value of unusual time range and allow deployers to overreload these values ​​by initializing parameters. To accomplish this, the corresponding filter should have the following content: 1) Implement a class of the Filter interface. This class name is LateAccessFilter, as shown in Listing 9-9. This class's init method reads StartTime and EndTime initialization parameters. It tries to analyze these values ​​as init, if these parameters are null or unformatted to integers, which uses the default value. Then, it will start and end events, FilterConfig, ServletContext, and filter names into the fields of the filter. Finally, LateAccessFilter provides an air to the Destroy method. 2) Filter behavior in the DOFILTER method. This method looks for the current event to see if it is in the range given in the start time and end event, if yes, print a log entry. 3) Call the DOFILTER method of Filterchain. After printing a report, this filter calls the next filter in the DOFILTER method of Filterchain (if there is no more filter, activate the servlet or JSP page). 4) Register the web application home page; define the initialization parameters. First, the FILTER element will be associated with the name LateAccessFilter with the class beservlets.filters.lateAccessFilter. The Filter element also contains two init-param sub-elements: a defined startTime parameter, another definition endtime parameter. Because people who will access the Filterrus home page are programmers, consider the abnormal time range between 2:00 am to 10:00. Finally, the filter-mapping element uses the ULR-PATTERN sub-element that is /index.jsp, associated with the web application home page. See the program list 9-10.5) Ending the activator Servervet. This has been introduced in Section 2, no longer repeat. When this web application is deployed on an external server and attached to the logging filter, the client will generate an item in the log file in the log file, such as "Warning: Hacker6.filtersrus.com Accessed HTTP: //www.filtersrus.com/filters/index.jsp on Oct 30,2001 9:22:09 am. ".</p> <p>Program List 9-9 LateAccessFilter.javaPackage MoreServlets.Filters; Import Java.io. *; Import Javax.Servlet. *; Import Javax.Servlet.http. *; Import Java.util. *; Import Java.Text. *; ** Filter that keeps track of accesses that occur * at unusual hours * / public class LateAccessFilter implements Filter {private FilterConfig config;. private ServletContext context; private int startTime, endTime; private DateFormat formatter; public void doFilter (ServletRequest request, ServletResponse response , FilterChain chain) throws ServletException, IOException {HttpServletRequest req = (HttpServletRequest) request; GregorianCalendar calendar = new GregorianCalendar (); int currentTime = calendar.get (calendar.HOUR_OF_DAY); if (isUnusualTime (currentTime, startTime, endTime)) {context .log ("Warning:" Req.getRemoteHost () "Accessed" Req.getRequestURL () "on" formatter.format (Calendar.getTime ()));} chain.do Filter (request, response);} public void init (FilterConfig config) throws ServletException {this.config = config; context = config.getServletContext (); formatter = DateFormat.getDateTimeInstance (DateFormat.MEDIUM, DateFormat.MEDIUM); try {startTime = Integer.parseInt (config.getInitParameter ( "startTime")); endTime = Integer.parseInt (config.getInitParameter ( "endTime"));} catch (NumberFormatException nfe) {// Malformed or null // Default: access at or After 10 Pm But Before 6 AM // is considered unusual. starttime = 22; // 10:00 PM endtime = 6;</p> <p>// 6:00 am}} public void destroy () {} // Is the current time between the start and end // times that are marked as abnormal access times? Private boolean isUnusualTime (int currentTime, int startTime, int endTime) {// if the start time is less The end time (ie, // the isy Tween on the same day), the the // current time is considered unusual if it is // Between the start and end Times. If (StartTime <endtime) {return (currenttime> = starttime) && (currenttime <endtime);} // if the start time is get Time or equal to the // end day (IE, The Start Time is on One Day and // the end time is on the next day), then the current // time is considered unusual if it is NOT between // the end and start times else {return). (isUnusualTime (currentTime, endTime, startTime!); }}} Listing 9-10 Web.xml (Excerpt of the filter for access) <? 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 "" - ... -> "LateAccessFilter" for moreservlets.filter.lateAccessfilter. Supply two initialization parameters: StartTime and endtime. -> <filter> <filter-name> LateAccessFilter < / filter-name> <filter-class> moreservlets.filters.lateAccessfilter </ filter-class> <init-param> <param-name> StartTime </ param-name> <param-value> 2 </ param-value></p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-56540.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="56540" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.035</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'M4Uk0emhBwh7VTjPZ5cMmo1_2FMPiFcxc4H1_2BQgu6os0wTtr5dCRTczEJbVIE1ucCaJoLlFVmHcBxo7Lnehej_2Biw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>