Servlet Filter Filters

Source: Internet
Author: User
Tags md5 encryption

Servlet Filter
Three technologies described in the Java EE servlet specification, Servlet Filter Listener
Servlet technology is the generation of dynamic Web resources
Filter technology to intercept server Web resources (permission control)
Filter, also known as filters, is the most practical technology in Servlet technology, Web developers through the filter technology, Web server management of all Web resources: such as JSP, Servlet, static picture files or static HTML files, etc. to intercept, So that some special functions can be realized. For example, the implementation of URL-level access control, filtering sensitive words, compressed response information and other advanced features.

Filter Implementation principle
The Servlet API provides a filter interface that, when developing a Web application, if the Java class is written to implement this interface, the Java class is called filter filter. Filter technology enables developers to intercept requests and responses to access before they access a target resource.
The filter interface has a Dofilter method that, when the developer writes the filter and configures which Web resource (intercept URL) to intercept, the Web server invokes the Dofilter method of the filter every time before invoking the Web resource, so Writing code within this method can do the following: 1. Let a piece of code execute before invoking the target resource
2, whether to invoke the target resource (that is, whether to let the user access the Web resource).
When the Web server calls the Dofilter method, a Filterchain object is passed in, and the Filterchain object is the most important object in the filter interface, and it also provides a Dofilter method. The developer can decide whether to call this method on demand or not, and the Web server invokes the Web resource's service method, which means that the Web resource will be accessed or the Web resource will not be accessed.
3, after invoking the target resource, let a piece of code execute

Steps to write Filter
1, creating a JSP
2, implement the filter interface covering the Dofilter and other methods
3, configure the registration filter in Web. XML and filter the path of the target resource.
The filter is written and configured similar to the servlet, but note that the filter class creates the filter object when the server starts, and the servlet creates the object when it is accessed. When the filter interception is configured, when the request accesses the target resource, the filters and target resources constitute the call chain object, the Dofilter method of the filter is executed first, when the target resource needs to be called, that is, when the next link of the call chain needs to be accessed. The Dofilter method of the Filterchain object needs to be called in the Dofilter method.
Multiple filters can be configured on the same Web resource in a single filter call chain. The order in which the filters are executed is determined by the mapping registration order of the filters in Web. Xml.

The life cycle of the filter
1, when the server Web application starts, it creates an instance of the filter object and calls the Init method.
2, when accessing the target resource, the Dofilter method performs interception filtering, each request executes once
3, the Detory method is executed when the server shuts down

Filterconfig interface
When you configure the filter, you can use <init-param> to configure some initialization parameters for the filter, and when the Web container instantiates the filter object and calls its Init method, The Filterconfig object that encapsulates the Fiter initialization parameter is passed in to get some information about the filter object.
Getfiltername (); Gets the name of the filter
Getinitparamter (String name); Gets the initialization parameter value of the specified name, no return null exists
Enumeration Getinitparameternames (); An enumeration collection that returns the names of all initialization parameters of a filter
Getservletcontext (); Returns the reference object of the servlet context used to read the resource.

Configure Filter-mapping
element is used to set a resource that the Filter is responsible for intercepting. A filter interception resource can be specified in two ways: a Servlet name and a request path for resource access, a Web resource can configure multiple filters, and a filter can also configure multiple Web resources
The <filter-name> child element 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 blocked by filter (the URL style associated with the filter)
<servlet-name> Specifies the name of the servlet that the filter intercepts.
<dispatcher> specifies how the resource that the filter intercepts is called by the Servlet container, which can be one of Request,include,forward and error, the default request. Users can set multiple <dispatcher> child elements to specify the Filter to intercept multiple calls to the resource.

<dispatcher> the values that child elements can set and their meanings:
REQUEST: When the user accesses the page directly, the Web container invokes the filter. If the target resource is accessed through the include () or forward () method of RequestDispatcher, then the filter is not called.
INCLUDE: The filter will be called if the target resource is accessed through the RequestDispatcher include () method. In addition, the filter is not called.
FORWARD: If the target resource is accessed through the RequestDispatcher FORWARD () method, then the filter will be called and the filter will not be called.
Error: If the target resource is called through a declarative exception handling mechanism, then the filter will be called. In addition, the filter is not called.

Filter Common applications
1, unified all-station character-coded filter
Specify which character encoding to use to handle the Chinese problem of the HTML form request parameter by configuring the parameter encoding
2, prevent the browser from caching all dynamic page filters:
There are 3 HTTP response header fields that can prevent the browser from caching the current page, and their sample code in the Servlet is as follows: Response.setdateheader ("Expires",-1);
Response.setheader ("Cache-control", "No-cache");
Response.setheader ("Pragma", "No-cache");
Not all browsers can fully support the above three response headers, so it is best to use the above three response headers at the same time. Expires Data header: Value GMT time value, 1 refers to browser do not cache page Cache-control response header has two common values: No-cache refers to the browser does not cache the current page. Max-age:xxx refers to browser cache page xxx seconds
3, the filter that controls the static resources in the browser cache page:
Scenario: Some dynamic pages refer to some pictures or CSS files to decorate the page effect, these images and CSS files are often unchanged, so to alleviate the pressure on the server, you can use the filter control browser to cache these files to improve the performance of the server.
4, realize the user automatic landing filter
After the user login is successful, send the user name, password in the form of Cookis to the client to write a filter, the filter method to check whether the cookie with the user name, password information, if present, call the business layer login method, When the login is successful, the user object (that is, the login mark) is stored in the session to realize the automatic login of the program.
5,MD5 encryption
/**
* Encryption using MD5 algorithm
*
* @param plaintext
* Encrypt original text
* @return Encryption text
*/public static string MD5 (string plaintext) {
byte[] secretbytes = null;
try {
Secretbytes = messagedigest.getinstance ("MD5"). Digest (Plaintext.getbytes ());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException ("No MD5 this algorithm!") ");
}
return new BigInteger (1, secretbytes). toString (16);
}
6,base64, commonly used to encode and encrypt information transmitted over a network
Example: User name, password, download software address, etc.
Base64encoder encoder = new Base64encoder ();
String s = "AAA";
String S1 = Encoder.encode (S.getbytes ());
Out.println (S1);
Base64decoder decoder = new Base64decoder ();
String s2 = new String (Decoder.decodebuffer (S1));
OUT.PRINTLN (S2);
7, use filter to implement URL-level permission authentication
Use filter to implement URL-level permission authentication scenarios: In real-world development we often map some of the servlets that perform sensitive operations to special directories and use filter to protect these special directories, restricting access to resources in those directories only to those who have access. Thus, a URL-level permission function is implemented in our system. Requirements: To make filter universal, filter-protected resources and corresponding access rights are configured in the form of the filter parameter.

Servlet Filter Filters

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.