Chuanzhi podcast java web Filter

Source: Internet
Author: User

It is not easy to use at all. Servlet should have been created to simplify the work! I thought it was a problem with my design framework. The next day I asked Fang, who was actually using some questions. For example, to display the access count, I write it as a Servlet separately. The Servlet. include will reference the counted Servlet whenever it is needed. However, this will always cause some problems and inconvenience in use. For example, the include Servlet must use the same stream. If forward is used, any output will be invalid.
At that time, instructor Fang suggested writing some functions together. But I finally mentioned the filter. At that time, I became interested in the filter. Today, I finally got a glimpse of it! People like it!
ServletFilter, Servlet filter:
Filter is also called a Filter. It is the most exciting technology in Servlet technology. WEB developers can use the Filter technology to manage all web resources on web servers: 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.
ServletAPI provides a Filter interface. The Servlet that implements this interface is a Filter. The attacker can access the WEB application as follows:
As shown in the figure, as long as we write a filter, We can filter all connections that access WEB applications. For example, user access permissions, unified WEB code...
How does Filter implement interception?
The Servlet implementing the Filter interface is a Filter, because the Filter interface has a doFilter (ServletRequest request, ServletResponse response, FilterChain chain) method, as long as the user accesses us on the web. in xml, the server will call the doFilter method of the filter. Here we implement the excessive function code. When we call the chain. doFilter (request, response); method, we will reverse the request to the server and then call the equivalent Servlet. If this method is not called, the user's request is rejected.
Getting started with Filter development:
To add a filter to a WEB application, perform the following two steps:
1. Compile the Servlet-Filter that implements the Filter interface.
2. Configure the filter in web. xml:
(1). <filter> tag Extender
(2). <filter-mapping> register the ing directory of the filter, which is the same as registering the Servlet.
In actual WEB applications, we may need to write multiple transfer handlers, such as: 1. Uniform WEB encoding filters (over all accesses) 2. User access permission management. In this way, user access needs to be filtered by filter 1 and then filtered by filter 2. DoFilter has a FilterChain parameter, which is a filter chain generated by the server in sequence based on the filters configured in web. xml. When we call chain in the doFilter method. doFilter (request, response); when the method is used, the server will find whether there is a filter in the filter chain. If there is a filter, the server will call the corresponding Servlet to process the user request.
Other details of the Filter interface:
1. The Init (FilterConfig filterConfig) method of Filter:
Like the Servlet Init method, the Filter instance is called during creation and then stored in the memory until the server is restarted or shut down. Different from Servlet, the server will instantiate all filters when it is started, and Servlet will be instantiated only when the user accesses it for the first time. We can use <init-param> in web. xml to initialize the Filter parameter, which can be obtained through FilterConfig.
FilterConfig methods include:
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.
2. The destroy () method of Filter:
This method is called before the Filter is destroyed when the server is restarted or shut down.
Compile the Filter exercise program:
1. Compile a Filter for uniform WEB character encoding:
Copy codeThe Code is as follows:
Package cn. itcast. cc. 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;
Import javax. servlet. http. HttpServletResponse;
Public class Encoding implements Filter {
Public void destroy (){
// TODO Auto-generated method stub
}
Public void doFilter (ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// Parameter conversion, because it must be an Http request.
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
// Set the request and response encoding to UTF-8.
Request. setCharacterEncoding ("UTF-8 ");
Response. setCharacterEncoding ("UTF-8 ");
Response. setContentType ("text/html; charset = UTF-8 ");
// Submit the settings to the server.
Arg2.doFilter (arg0, arg1 );
}
Public void init (FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}

2. Configure the web. xml file and add the following parts:
Copy codeThe Code is as follows:
<Filter>
<Filter-name> encoding </filter-name>
<Filter-class> cn. itcast. cc. filter. Encoding </filter-class>
</Filter>
<Filter-mapping>
<Filter-name> encoding </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>

3. The above is a simple usage of Filter, and advanced applications will be discussed later.
Advanced Filter development:
// Parameter conversion, because it must be an Http request.
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
The above two pieces of code are because we already know that request and response are two Http request objects encapsulated by the server. We have expanded its functions. If we do not know who created the request and response, how should we expand their functions? There are two ways to expand:
1. Write a subclass to overwrite the method to be overwritten.
2. Use the Decorator design mode to expand the functions we want.
Decorator design mode:
Sometimes we cannot use method 1, because we do not know the break class of an object. For example, it is an interface object and who is the implementation class ?. So we 'd better use method 2. Before that, we had access to the factory design patterns and Singleton design patterns. Java is the perfect embodiment of advanced applications. What is the Decorator design pattern? The Chinese name is the "decoration" mode. We will use this mode to expand the function of the request:
1. We implement the inheritance request interface type ServletRequest. Oh, my God, there are too many methods for ServletRequest. Do we need to implement every method? Servlet designers think of this and provide us with a packaging class-HttpServletRequestWrapper. Let's use it as the parent class!
2. Add an HttpServletRequest member to the custom class, because we need to decorate it.
3. Compile the method I want to cover, that is, the method we want to provide special functions.
For example, the filter of uniform WEB encoding compiled above is faulty. If we submit a form and the form submission method is GET, setting the request Encoding does not work. So here we use the Decorator design mode to improve the unified encoding function:
Compile the custom class MyServletRequest. java:
Copy codeThe Code is as follows:
Class MyServletRequest extends HttpServletRequestWrapper {
// Objects to be decorated
HttpServletRequest myrequest;
Public MyServletRequest (HttpServletRequest request ){
Super (request );
This. myrequest = request;
}
// Functions to be enhanced
@ Override
Public String getParameter (String name ){
// Use the decorated member to obtain data
String value = this. myrequest. getParameter (name );
If (value = null)
Return null;
// Return after Transcoding
Try {
Value = new String (value. getBytes ("ISO8859-1"), "UTF-8 ");
} Catch (UnsupportedEncodingException e ){
E. printStackTrace ();
}
Return value;
}
}

The code for modifying the Encoding. java filter is as follows:
Copy codeThe Code is as follows:
Public class Encoding implements Filter {
Public void destroy (){
// TODO Auto-generated method stub
}
Public void doFilter (ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
Arg2.doFilter (new MyServletRequest (HttpServletRequest) request), arg1 );
}
Public void init (FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}

You can see that the Decorator design mode is powerful! This part belongs to the advanced application of Filter. The course will explain the advanced application of Filter tomorrow. I didn't think so much, I thought that the request and response are enough. Even if they are enough, the efficiency and Code are not beautiful enough. In addition, these advanced applications become more beautiful, programming and maintenance are very convenient!
The course content is still wonderful, although the content of the teacher has already been understood. However, most of the students still cannot afford it because I have some software development experience and I feel a little relaxed after learning it. Because I learned my unfamiliar basic knowledge the other day, I still deserve it when I got to the advanced application! Desktop development, WEB applications, and program logic are the same. However, the workflow is not the same. More is the need for exercises. Today, instructor Fang has left homework for everyone. The content is to modify the automatic logon and user permission management of the last exercise. Okay, I should do my homework ....

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.