JAVA learning Analysis of Filter, java Analysis of filter

Source: Internet
Author: User

JAVA learning Analysis of Filter, java Analysis of filter

The previous blog learned about Servlet. This time, we will take a look at the Filter. Simply put, Filter is a Servlet specification technology, not a Servlet. It is also called a filter. It is used to change a request and modify a response. It can pre-process a request before it reaches the servlet, or it can process response when response leaves the servlet.

I. Lifecycle

The Servlet lifecycle written in the previous article is similar to that of Servlet:

1. Load the Filter instance when starting the server and call the Init () method to initialize the instance. (The Filter instance is prior to the Servlet)

2. Only the method doFilter () is called for processing each request.

3. Call the destroy () method when stopping the server to destroy the instance. (The instance is destroyed later than Servlet)

(Filter implements the Filter interface of the javax. servlet package, including methods: init (), doFilte (), destroy ())

Ii. How to Use Filter

The following uses adding a user as an example to compare the differences before and after use:

1. Do not use Filter:

2. Use Filter:

 

Compare the convenience brought by the use of Filter: we know that a system cannot only add user functions. We also have many functions to be implemented, such as Deleting Users and modifying users, however, setting the character set requires every function. If no Filter is available, we need to set the character set on every page. We will write the method of setting the character set in doFilter, after a request, each jsp page can configure the character set. Let's take a look at how a filter implements this function:

Packagecom. tgb. drp. util. filter; importjava. io. IOException; importjavax. servlet. filter; importjavax. servlet. filterChain; importjavax. servlet. filterConfig; importjavax. servlet. servletException; importjavax. servlet. servletRequest; importjavax. servlet. servletResponse;/*** use Filter to uniformly process character sets * @ author YoungJong **/public classCharsetEncodingFilter implements Filter {private String encoding;/*** destruction method */publicvoid destroy () {// TODO Auto-generated method stub}/*** implement doFilter */publicvoid doFilter (ServletRequest request, ServletResponse response, FilterChainchain) throws IOException, ServletException {// set the character set request. setCharacterEncoding ("GB18030"); // continue to run the chain. doFilter (request, response);}/*** Initialization method */publicvoid init (FilterConfig filterConfig) throws ServletException {// TODO Auto-generated method stub this. encoding = filterConfig. getInitParameter ("encoding"); System. out. println ("CharsetEncodingFilter. init () --> endcoding = "+ encoding );}}

Of course, we also need to configure it in web. xml:

 

<filter><filter-name>CharsetEncodingFilter</filter-name><filter-class>com.tgb.drp.util.filter.CharsetEncodingFilter</filter-class><init-param>     <param-name>encoding</param-name>     <param-value>GBK</param-value></init-param></filter>         <filter-mapping><filter-name>CharsetEncodingFilter</filter-name><url-pattern>*.jsp</url-pattern></filter-mapping> 

Iii. Comparison with servlet:

The same as servlet, they all need to implement interfaces, but Filter implements Filter, while Servlet implements HttpServlet. but the biggest difference between them is their role:

1. Servlet: It mainly processes client requests and sends the results to the client.

2. Filter: Before HttpServletRequest arrives at the Servlet, it intercepts the customer's HttpServletRequest. Before HttpServletResponse arrives at the client, it intercepts HttpServletResponse. It is mainly used for interception and subsequent transmission after corresponding processing.

 

It's almost the same content, but it's not that easy to stop ?! So let's make a conclusion: there is such a saying in the video: Filter represents a mode responsibility chain mode; Servlet represents a mode template method mode. We can still understand the responsibility chain embodied in Filter, but we still cannot fully understand the template method embodied in Serlet .. Silently grief ..


How to use java filter

Creating a filter involves the following five steps:
1) create a class to implement the Filter interface. This class requires three methods: doFilter, init, and destroy. The doFilter method contains the main filtering code (see step 1). The init method establishes the setting operation, while the destroy method is clear.
2) Put the filtering behavior in the doFilter method. The first parameter of the doFilter method is the ServletRequest object. This object provides the filter with full access to the incoming information (including form data, cookies, 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 of the FilterChain object. The doFilter method of the Filter interface takes a FilterChain object as its parameter. When the doFilter method of this object is called, The next related filter is activated. If no other filter is associated with the servlet or JSP page, the servlet or JSP page is activated.
4) register a filter for the servlet and JSP pages. Use the filter and filter-mapping elements in the deployment descriptor file (web. xml.
5) disable the activator servlet. Prevents users from bypassing the filter settings using the default servlet URL.

What is the role of filter in JAVA?

You are talking about servlet filter. You should know the servlet. The request and response objects in the servlet are clear about what they represent. Then, you will understand the following explanation:
Filter allows you to change a request and modify a response. filter is not a servlet. It cannot generate a response. It can pre-process a request before it reaches the servlet, or process response when it leaves the servlet. in other words, the filter is actually a "servlet chaining" (servlet chain ).

In layman's terms, filter is equivalent to a gas station, request is a road, response is a road, and the destination is servlet. You can control where the gas station is located and what data operations can be performed.

The following are some common application scenarios of servlet filter,
(1) authentication Filter
(2) log and audit Filter
(3) image conversion Filter
(4) data compression Filter
(5) Password Filter
(6) token Filter
(7) Filter that triggers Resource Access Events
(8) XSLT Filter
(9) media type chain Filter
Of course, you can also discover its new role on your own.

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.