Home >Java >javaTutorial >Detailed introduction to Filter in JavaWeb
This article mainly introduces the detailed explanation of JavaWeb FilterFilter, and analyzes the usage skills of JavaWeb Filter with examples. It is of great practical value and friends in need can refer to it.
I originally planned to summarize this articleJSP. Since JSP has a lot of content, and I want to run at night to lose weight, I will introduce Filter and its usage examples today. There is still some time to exercise. Closer to home, the filter literally has the function of blocking and filtering. It can be regarded as the blocking wizard of JavaWeb.
1. Origin
#The client initiates a request, so the server cannot respond to all requests. Interception processing can not only alleviate the problem of the server It can also protect the security of the data. Similarly, when the server responds to the client, it sometimes needs to be filtered, such as adding watermarks to our common pictures. In order to deal with these problems, filters appeared. Sometimes not only one layer of requests and responses is filtered, but multiple layers may be filtered, so the concept of filter chain (FilterChain) is proposed.
II , Use
Be familiar with its function before using it. The filter function will pass through the filter chain in sequence before the request reaches Servlet and before the response reaches the browser. Somewhat similar to httpmodule in asp.net. Using Filter mainly implements javax.servlet.filterinterface. Looking at API, you can see that there are 3 methods.
1.public void init(FilterConfig filterConfig) throws ServletException
Called by the Web container to indicate the filter that will be put into the service . The servlet container calls the init method only once after instantiating the filter. The init method must complete successfully before asking the filter to do any filtering work. If the init method throws a ServletException or does not return within the time period defined by the web container, the web container cannot put the filter into the service. This is somewhat similar to the life cycle of Servlet. It is only initialized once and destroy() is also executed once.
2.public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException
Every time due to a certain error at the end of the chain When a client request for a resource passes a request/response pair through the chain, the container calls the Filter's doFilter method. The FilterChain passed into this method allows the Filter to pass the request and response to the next entity in the chain.
A typical implementation of this method follows the following pattern:
1. Check the request
2. Selectively send the request with a custom implementation Object Wrapping into filter content or headers for input filtering
3. Optionally wrap response objects with custom implementations into filter content for output filtering Or in the header
4. a) You can either use the FilterChain object (chain.doFilter()) to call the next entity in the chain,
4. b) Also It is possible to block request processing by not passing the request/response pair to the next entity in the filter chain
5. Set headers on the response directly after calling the next entity in the filter chain .
3.public void destroy()
Called by the web container to indicate the filter to be taken out of the service. This method is called only once after all threads in the filter's doFilter method have exited, or after the timeout period has elapsed. After calling this method, the web container will not call the doFilter method on this filter instance. This method provides an opportunity for the filter to clean up all resources it holds (such as memory, file handles, and threads) and ensures that any persistent state is kept in sync with the current state of the filter in memory.
3. Cases
There are many places to use filters, so I won’t give examples one by one here. The following demo is in the previous blog Based on the HelloWorld project, the anti-leeching function is implemented to experience the use of Filter.
1.Preparation
In the HelloWolrd projectAdd a new folder and put two pictures in the folder, one err.png and one test.png. The two pictures are as follows
2. Create Filter
There is no new Filter package here. Create the Filter file MyFilter directly in the com.test.cyw package in the previous blog. It should be to create a package specifically to manage Filter. Well, this is just for testing. After the creation is completed, you can see that MyFilter inherits Filter.
public class MyFilter implements Filter
3. Implement anti-hotlinking in doFilter
package com.test.cyw; 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.annotation.WebFilter; import javax.servlet.http.*; /*@WebFilter("/MyFilter")*/ public class MyFilter implements Filter { public MyFilter() { } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req=(HttpServletRequest)request; HttpServletResponse res=(HttpServletResponse)response; String referer=req.getHeader("referer");//链接来源地址 if(referer==null||!referer.contains(req.getServerName())) { req.getRequestDispatcher("/Images/err.png").forward(req, res); return; } chain.doFilter(req, res); } public void init(FilterConfig fConfig) throws ServletException { } }
4.Filter configuration
The above just creates a class that implements the Filter interface. How to let Tomcat know? This is similar to Servlet and needs to be configured in Web.xml. It's a bit the same as configuring a servlet.
<filter> <filter-name>MyFilter</filter-name> <filter-class>com.test.cyw.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/Images/*</url-pattern> </filter-mapping>
5. Test
Create a new test.jsp file, display img in jsp, and it can be displayed normally
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <img alt="防盗链" src="Images/test.png" width="400"> </body> </html>
If you directly enter the address of test.png in the browser, err.png
# will be displayed ##4. Problems Encountered
At the beginning, due to the wrong address, the image displayed in Google Chrome test.jsp was also the err.png picture, but when I When I refreshed the page, there was still no change. This made me very puzzled. Sometimes restarting Tomca doesn't work. I tried it several times and it still works like this. When it really doesn't work, I tried it with IE but didn't expect the display to be correct. It turns out that Google Chrome has acache, which caused the display to be incorrect.
5. Summary
Filter has many uses, and there are many examples on the Internet. When doing projects, you can first implement some commonly used ones such as watermarks, etc. When using it, you only need to configure the xml to solve the problem, which is very convenient.The above is the detailed content of Detailed introduction to Filter in JavaWeb. For more information, please follow other related articles on the PHP Chinese website!