Javaweb -- filter ing and javaweb Filter

Source: Internet
Author: User

Javaweb -- filter ing and javaweb Filter

What is a filter?

Filter: literally, it can be understood as filtering water with impurities, leaving clean water. From the IT perspective. Filter: a component that is in the middle of the source data (such as the database) and target data (display page. For a Web application, a filter is a Web component residing on the server. It can intercept the request and response information between the client and the resource and filter the information.

When the Web Container (server) receives a request for resource data, it determines whether the filter is associated with the request. If yes, it sends the request to the filter for processing, then, in the filter, you can change the request content and then send the request to the target resource.

[Request-> Web Container-> filter-> Target Resource]

When the target resource responds to the request, the Web Container will also forward it to the filter. In the filter, you can change the response content and then send it to the display page.

[Target resource-> Web Container-> filter-> display page]

Lifecycle of a filter

The lifecycle of the filter is the same as that of the web Container. When the web Container starts, the web of the application will be read. xml configuration file. If a filter is configured here, the container will execute instantiation and call the init method of the filter.

Then, the user executes the doFilter method of the filter for each request.

When the web container is destroyed, the destroy method is executed to release the resource.

 

Filter Execution Process

 

After a user sends a request that meets the filter rules, the web Container executes the doFilter method in the filter to perform specific operations. Then, it calls FilterChain. doFilter to forward the request to the web container. After the web container is executed, the resource is returned to the filter and then displayed to the user.

Simple filter instance

The following code shows how to write a filter.

First, you need to create a Filter that integrates the javax. servlet. Filter interface. Three methods must be implemented: init () doFilter () destroy ()

Package com. filter; import java. io. IOException; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import javax. servlet. http. httpServletRequest; // The definition class inherits the Filter and defines the Filter public class myFilter implements Filter {public myFilter () {}// destroy public void destroy () {System. out. println ("myFilter destroy");} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System. out. println ("myFilter start .. dofilter "); // request to allow HttpServletRequest req = (HttpServletRequest) request; req. getRequestDispatcher ("index. jsp "). forward (request, response); System. out. println ("myFilter end .. fofilter ");} // initialize public void init (FilterConfig fConfig) throws ServletException {System. out. println ("myFilter init ");}}

The init () method is called when the web Container instantiates the filter.

The doFilter () method is called every time a request is sent and the filtering rule is met.

The destroy () method is called when the web container is closed.

 

Then, configure the corresponding options in web. xml. If it is servlet3.0, the filter can be configured using annotations.

<filter>    <filter-name>myFilter</filter-name>    <filter-class>com.filter.myFilter</filter-class></filter><filter-mapping>    <filter-name>myFilter</filter-name>    <url-pattern>/index.jsp</url-pattern></filter-mapping>

There are several essential items:

The filter is configured in <filter>. filter-name indicates the name of the filter, and filter-class indicates the class of the filter;

In <filter-mapping>, the filter ing rule is configured. filter-name indicates the name of the filter, and url-pattern indicates the filtered path, dispatcher is a filter classification (mainly including four types)

Here we will first describe the filter rules. If you want to filter all requests, you can write /*

If you want to filter index. jsp index.html, you can write/index *

If you only want to filter index. jsp, you can write it as/index. jsp.

Second, after configuration, create index. jsp

<% @ Page language = "java" contentType = "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1" %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> Finally, after starting the web Container, you can find on the console that the init method is executed during initialization.

 

 

 

 

 

 

 

Invincible split line -------------------------------------------------------------------------------

Application of filter in web

Application of filters in Web development:

 

Filters are newly added from the Servlet2.3 specification and are enhanced in the Servlet2.4 specification. Below is

The Application of Filter in Web development.

 

Filter Overview:

A filter is an intermediate component that filters between source and target data. For a Web application, a filter is a Web component that resides on the server. It can intercept the request and response information between the client and resources and filter the information.

 

When a Web Container receives a request for a resource, it determines whether a filter is associated with the resource. If yes, the container will send the request to the filter for processing. In the filter, you can change the request content, or reset the request header information, and then send the request to the target resource. When the target resource responds to the request, the container will also forward the response to the filter first, and then in the filter, you can convert the response content and then send the response to the client.

 

Some main applications of filters in Web development:

 

· Uniformly authenticate user requests.

 

· Record and review user access requests.

 

· Filter or replace user data.

 

· Convert the image format.

 

· Compress the response content to reduce the transmission volume.

 

· Encrypt and decrypt requests or responses

 

· Triggering resource access is an event.

 

· Apply XSLT to XML output.

 

Filter API:

 

The interfaces and classes related to filter development are included in the javax. serlvet and javax. servlet. http packages. They mainly include the following interfaces and classes.

 

· Javax. servlet. Filter Interface

 

· Javax. servlet. FilterConfig Interface

 

· Javax. servlet. FilterChain Interface

 

· Javax. servlet. ServletRequestWrapper class

 

· Javax. servlet. ServletResponseWrapper class

 

· Javax. servlet. http. HttpServletRequestWrapper class

 

· Javax. servlet. http. HttpServletResponseWrapper class

 

Filter interface:

 

The javax. servlet. Filter interface must be implemented for the development Filter, which is similar to the javax. servlet. servlet interface implemented by the Development Servlet. Provides a public constructor without parameters. The Filter interface defines the following three methods:

 

· Public void init (FilterConfig filterConfig) throws ServletException

 

The Web Container calls this method to initialize the filter. When the container calls this method, it passes the FIlterConfig object to the filter. The usage of FilterConfig is similar to that of ServletConfig (see previous content. The FilterConfig object can be used to obtain the ServletContext object and the initialization parameters of the filter configured in the deployment descriptor. In this method, a ServletException exception can be thrown, notifying the container that the filter cannot work normally.

 

· Public void doFilter (ServletRequest request, ServletResponse

Response, FilterChain chain) throws java. io. IOException, ServletException

 

The doFilter () method is similar to the service () method of the Servlet interface. When the client requests the target resource, the container will call the doFilter () method of the filter associated with the target resource. After a specific operation is completed, you can call the chain. doFilter (request, response) sends the request to the next filter (or target resource). You can also directly return the response information to the client, or use the forward () and include () Methods of RequestDispatcher, and the sendRedirect () method of HttpServletResponse redirects requests to other resources. Note that the request and Response parameters of this method are ServletRequest and ServletResponse. That is to say, the use of filters does not depend on specific protocols.

 

· Public void destroy ()

 

The Web Container calls this method to indicate that the lifecycle of the filter is over. In this method, resources used by the filter can be released. Unlike Servlet development, the Filter interface does not have an implementation class for inheritance. You need to develop a Filter,

You can only directly implement the Filter interface.

 


FilterConfig interface:

The javax. servlet. FilterConfig interface is similar to the javax. servlet. ServletConfig interface and is used to pass information to the filter during initialization. The FilterConfig interface is implemented by a container. The container uses it as a parameter to pass it into the init () method of the filter object. The FilterConfig interface defines four methods:

 

· Public java. lang. String getFilterName ()

 

Obtain the name of the filter specified in the descriptor.

 

· Public java. lang. String getInitParameter (java. lang. String name)


Return the value of the initialization parameter named name specified in the deployment description. If no data exists, null is returned.

 

· Public java. util. Enumeration getInitParameterNames ()


Returns an enumeration set of the names of all initialization parameters of the filter.

 

· Public ServletContext getServletContext ()


Returns the reference of the Servlet context object.

 

 

 

FilterChain interface:

 

The FilterChain interface is implemented by the container. The container passes its instance as a parameter to the doFilter () method of the filter object. The filter object uses the FilterChain object to call the next filter in the filter chain.

Is the last filter in the chain, then the target resource will be called. The FilterChain interface has only one method, as shown below:

 

· Public void doFilter (ServletRequest request, ServletResponse response)

Throws java. io. IOException

 

By calling this method, the next filter in the filter chain is called. If it is the last filter, the target resource is called.

 


Filter deployment:

 

After implementing a filter, You need to configure the filter in the deployment descriptor. This is done through the <filter> and <filter-mapping> elements.

The <filter> element is used to declare a filter in a Web application.


In the <filter> element, the <description>, <display-name>, and <icon> elements are the same as those in previous servlet configurations. <Filter-name> specifies a name for the filter. The content of this element cannot be blank.

The <filter-class> element is used to specify the full qualified class name of the filter. The <init-param> element is used to specify initialization parameters for the filter. Its sub-element <param-name> specifies the parameter name and <param-value> specifies the Parameter

Number. In the filter, you can use the FilterConfig interface object to access initialization parameters.

 

 

 

The following is a small example of the <filte> element:

<Filter>
<Filter-name> testFitler </filter-name>
<Filter-class> org. test. TestFiter </filter-class>
<Init-param>
<Param-name> word_file </param-name>
<Param-value>/WEB-INF/wordtxt </param-value>
</Init-param>
</Filter>

 

The Servlet container creates only one instance for each filter declared in the deployment descriptor. Similar to Servlet, a container runs multiple threads on the same filter instance to serve multiple requests at the same time. Therefore, a filter is developed.

Pay attention to thread security issues.

 

The <filter-mapping> element is used to specify the url style or Servlet associated with the filter.

The value of the <filter-name> sub-element must be the name of the filter declared in the <filter> element.

You can select either the <url-pattern> element or the <servlet-name> element;

<Url-pattern> specifies the URL style associated with the filter;

The <servlet-name> element specifies the Servlet corresponding to the filter.

The filter is called by the container only when you access resources on the url specified by the <URL-pattern> element or the servlet specified by the <Servlet-name> element.

The <filter-mapping> element can also contain 0 to 4 <dispatcher>. It specifies the REQUEST method corresponding to the filter, which can be one of REQUEST, INCLUDE, FORWARD, and ERROR. The default value is REQUEST.

 

· REQUEST
When the user accesses the interface directly, the Web Container will call the filter. If the target resource is accessed through the include () or forward () method of RequestDispatcher, the filter will not be called.

 

· INCLUDE
If the target resource is accessed through the include () method of RequestDispatcher, the filter will be called. In addition, the filter will not be called.

 

· FORWARD
If the target resource is accessed through the RequestDispatcher's forward () method, the filter will be called and will not be called.

 

· ERROR
If the target resource is called through the declarative Exception Handling Mechanism, the filter will be called. In addition, the filter will not be called.


Example:

<Filter-mapping>
<Filter-name> testFilter </filter-name>
<Url-pattern>/test. jsp </url-pattern>
</Filter-mapping>
When you access the test. jsp page, the container will call the testFilter filter.

<Filter-mapping>
<Filter-name> testFilter </filter-name>
<Url-pattern>/index. jsp </url-pattern>
<Dispatcher> REQUEST </dispatcher>
<Dispatcher> FORWARD </dispatcher>
</Filter-mapping>

When you directly access the index. jsp page or use the forward () method of RequestDispatcher to access the page, the container will call the testFilter filter.

Content Source: (for fear of loss, please remember)

Http://www.ylzx8.cn/web/web/979338.html

Http://www.cnblogs.com/xing901022/p/4482057.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.