Javaweb --- filter, javaweb
Reposted at: http://www.cnblogs.com/xdp-gacl/p/3948353.html、filterintroduction
Filter is also called a Filter. It is the most exciting technology in Servlet technology. WEB developers use the Filter technology to manage all web resources on web servers, such as Jsp, Servlet, static image files or static html files are intercepted to implement some special functions. For example, some advanced functions such as URL-level access control, filtering sensitive words, and compressing response information are implemented.
The Servlet API provides a Filter interface. When developing a web application, if the written Java class implements this interface, the java class is called a Filter. With the Filter technology, developers can intercept access requests and responses before accessing a target resource, as shown below:
2. How does a Filter implement interception?
The Filter interface has a doFilter method. After we compile the Filter and configure which web resource to intercept, the WEB server will call the service method of the web Resource each time, the doFilter method of filter is called first. Therefore, you can write code in this method to achieve the following purpose:
When the web server calls the doFilter method, it will pass in a filterChain object. The filterChain object is the most important object in the filter interface. It also provides a doFilter method, developers can decide whether to call this method as needed. When this method is called, the web server will call the service method of the web resource, that is, the web resource will be accessed, otherwise, the web resources will not be accessed.
3. Filter development Step 3.1
Filter development involves two steps:
Filter Example:
1 package me. gacl. web. filter; 2 3 import java. io. IOException; 4 5 import javax. servlet. filter; 6 import javax. servlet. filterChain; 7 import javax. servlet. filterConfig; 8 import javax. servlet. servletException; 9 import javax. servlet. servletRequest; 10 import javax. servlet. servletResponse; 11 12/** 13 * @ ClassName: FilterDemo0114 * @ Description: three typical applications of filter: 15*1. You can determine whether to call chain in filter based on conditions. doFilter (re Quest, response) method, 16 * Indicates whether to let the target resource execute 17*2. Before the target resource is executed, the request \ response can be preprocessed, then let the target resource be executed 18*3. After the target resource is executed, the execution results of the target resource can be captured to implement some special functions 19 * @ author: Lone Wolf 20 * @ date: */22 public class FilterDemo01 implements Filter {23 24 @ Override25 public void init (FilterConfig filterConfig) throws ServletException {26 System. out. println ("---- filter initialization ----"); 27} 28 29 @ Override30 public void doFilter (ServletRequest request, ServletResponse response, 31 FilterChain chain) throws IOException, ServletException {32 33 // perform some preprocessing on the request and response 34 request. setCharacterEncoding ("UTF-8"); 35 response. setCharacterEncoding ("UTF-8"); 36 response. setContentType ("text/html; charset = UTF-8"); 37 38 System. out. println ("FilterDemo01 before execution !!! "); 39 chain. doFilter (request, response); // Let the target resource be executed, allow 40 System. out. println (" FilterDemo01 after execution !!! "); 41} 42 43 @ Override44 public void destroy () {45 System. out. println (" ---- filter destruction ---- "); 46} 47}
Configure the filter in web. xml:
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <web-app version = "3.0" 3 xmlns = "http://java.sun.com/xml/ns/javaee" 4 xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" 5 xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 7 <display-name> </display-name> 8 <welcome-file-list> 9 <welcome-file> index. jsp </welcome-file> 10 </welcome-file-list> 11 12 <! -- Configure the filter --> 13 <filter> 14 <filter-name> FilterDemo01 </filter-name> 15 <filter-class> me. gacl. web. filter. filterDemo01 </filter-class> 16 </filter> 17 18 <! -- Ing filter --> 19 <filter-mapping> 20 <filter-name> FilterDemo01 </filter-name> 21 <! -- "/*" Indicates blocking all requests --> 22 <url-pattern>/* </url-pattern> 23 </filter-mapping> 24 25 </web-app>
3.2 Filter chain
In a web application, you can develop and compile multiple filters. These filters are called a Filter chain in combination.
The web server depends on the Filter in the web. the registration order in the xml file determines which Filter to call first. When the doFilter method of the first Filter is called, the web server creates a FilterChain object representing the Filter chain and passes it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server will check whether there is a filter in the FilterChain object. If there is a filter, the web server will call 2nd filters. If not, then the target resource is called.
4. lifecycle 4.1 of the Filter and creation of the Filter
Filter creation and destructionWEB Server. Web ApplicationsStart, The web ServerInstance Object for Filter CreationAnd call its init method to complete object initialization, so as to prepare for subsequent user requests to intercept,The filter object is created only once, and the init method is executed only once.. Through the parameters of the init method, you can obtain the FilterConfig object that represents the current filter configuration information.
4.2. Filter destruction
The Web Container calls the destroy method to destroy the Filter. The destroy method is executed only once in the lifecycle of the Filter. In the destroy method, resources used by the filter can be released.
4.3 FilterConfig Interface
When configuring the filter, you can use <init-param> to configure some initialization parameters for the filter. When the web Container instantiates the Filter object and calls its init method, the filterConfig object that encapsulates the filter initialization parameters is passed in. Therefore, when writing a filter, developers can use the filterConfig object method to obtain:
String getFilterName (): Get the filter Name.
String getInitParameter (String name): return the value of the initialization parameter specified in the deployment description. If no data exists, null is returned.
Enumeration getInitParameterNames (): returns an Enumeration set of the names of all initialization parameters of the filter.
Public ServletContext getServletContext (): return the reference of the Servlet context object.
Example: Use FilterConfig to obtain the filter configuration information
1 package me. gacl. web. filter; 2 3 import java. io. IOException; 4 import java. util. enumeration; 5 import javax. servlet. filter; 6 import javax. servlet. filterChain; 7 import javax. servlet. filterConfig; 8 import javax. servlet. servletException; 9 import javax. servlet. servletRequest; 10 import javax. servlet. servletResponse; 11 12 public class FilterDemo02 implements Filter {13 14/* Filter initialization 15 * @ see javax. se Rvlet. filter # init (javax. servlet. filterConfig) 16 */17 @ Override18 public void init (FilterConfig filterConfig) throws ServletException {19 System. out. println ("---- filter initialization ----"); 20/** 21 * <filter> 22 <filter-name> FilterDemo02 </filter-name> 23 <filter-class> me. gacl. web. filter. filterDemo02 </filter-class> 24 <! -- Configure the FilterDemo02 filter initialization parameter --> 25 <init-param> 26 <description> Configure the FilterDemo02 filter initialization parameter </description> 27 <param-name> name </param- name> 28 <param-value> gacl </param-value> 29 </init-param> 30 <init-param> 31 <description> Configure the initialization parameters of the FilterDemo02 filter </ description> 32 <param-name> like </param-name> 33 <param-value> java </param-value> 34 </init-param> 35 </filter> 36 37 <filter-mapping> 38 <filter-name> FilterDemo02 </filter-na Me> 39 <! -- "/*" Indicates blocking all requests --> 40 <url-pattern>/* </url-pattern> 41 </filter-mapping> 42 */43 // get the name of the filter is 44 String filterName = filterConfig. getFilterName (); 45 // get in web. the initialization parameter 46 String initParam1 = filterConfig configured in the xml file. getInitParameter ("name"); 47 String initParam2 = filterConfig. getInitParameter ("like"); 48 // return the enumerated set of the names of all initialization parameters of the filter. 49 Enumeration <String> initParameterNames = filterConfig. getInitParameterNames (); 50 51 System. out. println (filterName); 52 System. out. println (initParam1); 53 System. out. println (initParam2); 54 while (initParameterNames. hasMoreElements () {55 String paramName = (String) initParameterNames. nextElement (); 56 System. out. println (paramName); 57} 58} 59 60 @ Override61 public void doFilter (ServletRequest request, ServletResponse response, 62 FilterChain chain) throws IOException, ServletException {63 System. out. println ("FilterDemo02 before execution !!! "); 64 chain. doFilter (request, response); // Let the target resource be executed, allow 65 System. out. println (" FilterDemo02 after execution !!! "); 66} 67 68 @ Override69 public void destroy () {70 System. out. println (" ---- filter destruction ---- "); 71} 72}View Code
5. Filter deployment
The deployment of Filter is divided into two steps:
1. Register a Filter
2. ing Filter
5.1 register a Filter
After the Filter is developed, you must register it in the web. xml file to be called by the web server.
Register the Filter example in the web. xml file:
<Filter> <description> FilterDemo02 filter </description> <filter-name> FilterDemo02 </filter-name> <filter-class> me. gacl. web. filter. filterDemo02 </filter-class> <! -- Configure the FilterDemo02 filter initialization parameters --> <init-param> <description> Configure the FilterDemo02 filter initialization parameters </description> <param-name> name </param-name> <param-value> gacl </param-value> </init-param> <description> Configure the initialization parameters of the FilterDemo02 filter </description> <param-name> like </param-name> <param-value> java </param-value> </init-param> </filter>
<Description> used to add description information. The content of this element can be blank. <description> you can leave it empty.
<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 value. In the filter, you can use the FilterConfig interface object to access initialization parameters. If the filter does not need to specify the initialization parameter, the <init-param> element does not need to be configured.
5.2 ing Filter
After the Filter is registered in the web. xml file, you must map the Filter to the web. xml file.
<! -- Ing filter --> <filter-mapping> <filter-name> FilterDemo02 </filter-name> <! -- "/*" Indicates blocking all requests --> <url-pattern>/* </url-pattern> </filter-mapping>
The <filter-mapping> element is used to set the resources intercepted by a Filter. Resources intercepted by a Filter can be specified in two ways: Servlet name and Resource Access Request Path.
<Filter-name> the subelement is used to set the Registration name of the filter. The value must be the name of the filter declared in the <filter> element.
<Url-pattern> set the Request Path intercepted by the filter (the URL style associated with the filter)
<Servlet-name> specify the name of the Servlet intercepted by the filter.
<Dispatcher> specify the method in which the resource intercepted by the filter is called by the Servlet container. It can be one of REQUEST, INCLUDE, FORWARD, and ERROR. The default value is REQUEST. You can set multiple <dispatcher> sub-elements to specify filters to block multiple resource calling methods. As follows:
<filter-mapping> <filter-name>testFilter</filter-name> <url-pattern>/index.jsp</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>
<Dispatcher> values that can be set by sub-elements and their meanings: