1. Introduction
In Java Web development,Filter
It is a very important component for pre-processing or post-processing of requests and responses before they arrive at the Servlet or before the response returns to the client.
Filter
It can be used to implement various functions, such as logging, permission checking, encoding conversion, request header modification, etc. It’s like the layers of security checks at the airport, where passengers who come check and filter, carry illegal items, and do not buy air tickets, etc., will be blocked from entering.
How it works
Configuration:existConfigure in the file or using annotations
Filter
。
- exist
Medium configuration
<filter> <!--set upfilterAlias of--> <filter-name>LoggingFilter</filter-name> <!--filterbytecode path--> <filter-class></filter-class> </filter> <filter-mapping> <!--usefilterThe filter path corresponding to the alias,There can be multiple--> <filter-name>LoggingFilter</filter-name> <!--/*Indicates filtering all paths--> <url-pattern>/*</url-pattern> <!--What to filterservletAlias of--> <servlet-name>servlet1</servlet-name> </filter-mapping>
Use Notes@WebFilter
, It has the following commonly used values:
-
filterName
: The alias of filter is equivalent to the tag -
urlPatterns
: The resource url to be filtered is equivalent to the tag -
ServletNames
: The servlet alias to be filtered, equivalent to servletNames
@WebFilter( filterName = "loggingFilter", urlPatterns = {"/servlet1","*.html"}, servletNames = {"servlet1","Servlet2"} )
Intercept:
- When the request arrives,
Filter
Requests are intercepted and preprocessing logic is executed. - Some operations performed before the request reaches the target resource, such as checking whether the user has permission to access records, requests, and responses information
Let go:
-
Filter
You can choose whether to release the request to the target resource (such as a Servlet). It will be executed at this timeFilterChain
ofdoFilter
Method represents release. -
FilterChain
expressFilter
If there are other links for this resource, there are other links in the futureFilter
To filter, at this timedoFilter
The method will execute otherFilter
;If there is noFilter
To filter, it will be released and the target resource will be processed (such as servlet)
Post-processing:
- After the target resource (such as Servlet) has processed the request
-
Filter
Response can be post-processed
Life cycle
Including the firstcreate、Initialize、filteranddestroyFour stages.
stage | Corresponding method | Execution timing | Number of executions |
---|---|---|---|
Create an object | Constructor | When web application starts | 1 time |
Initialization method | void init(FilterConfig filterConfig) | Completed construction | 1 time |
Filter requests | void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) | Every request | repeatedly |
destroy | default void destroy() | When the web application is closed | 1 time |
When you pay special attention to itFilter
Created and initialized when the web application is started, this process only occurs once.
The order of execution
In a web project, multiple filters can be defined at the same time. When multiple filters filter the same resource, the working positions are successively formed, and a working chain is formed as a whole, which is called the filter chain (FilterChain)
- When configuring with configuration files
- The order of filters in the filter chain is determined by the order of definition of the <filter-mapping> tag
- When configuring using annotations
- Usually all filters are placed in one package. At this time, the execution order is the dictionary sort of class names, which is executed from small to large.
5. An example of a simple Filter
Case requirements:
When a user accesses a resource, check whether it logs in. If it is not logged in, it will jump to the login page. If it is logged in, it will be released.
@WebFilter("/*") public class CheckLoginFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //Transform downward, realize redirection, obtain session and other functions HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; // Check whether the user is logged in String user = (String) ().getAttribute("username"); if (user == null) { // The user is not logged in, redirect to the login page (() + "/login"); } else { // The user has logged in and released the request. Note that the doFilter method in FilterChain is called! ! (request, response); } } }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.