In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the function of Filter in Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the function of Filter in Java"?
Introduction to Filter
Filter, also known as filter, is the most practical technology in Servlet technology. WEB developers use Filter technology to intercept all web resources managed by web server, such as Jsp, Servlet, static picture files or static html files, so as to achieve some special functions. For example, it implements some advanced functions such as access control at URL level, filtering sensitive words, compressing response information and so on.
It is mainly used for pre-processing of user requests and post-processing of HttpServletResponse. The complete process of using Filter: Filter preprocesses the user request, then sends the request to Servlet for processing and generates a response, and finally Filter performs post-processing on the server response.
Filter function
Intercept the customer's HttpServletRequest before HttpServletRequest arrives at Servlet. Check the HttpServletRequest as needed, or you can modify the HttpServletRequest header and data. Intercept the HttpServletResponse before HttpServletResponse reaches the client. Check the HttpServletResponse as needed, or you can modify the HttpServletResponse header and data.
How to intercept function with the help of Filter
There is a doFilter method in the Filter interface. After the developer writes the Filter and configures which web resource to intercept, the WEB server calls the doFilter method of filter before calling the service method of the web resource. Therefore, writing code in this method can achieve the following purposes:
Let a piece of code execute before calling the target resource. Whether to call the target resource (that is, whether to let the user access the web resource).
When the web server calls the doFilter method, it will pass a filterChain object. 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 and call the method according to the requirements, then the web server will call the service method of the web resource, that is, the web resource will be accessed, otherwise the web resource will not be accessed.
Two steps in Filter Development
1. Write the java class to implement the Filter interface and implement its doFilter method.
two。 Use the and element in the web.xml file to register the written filter class and set the resources it can intercept.
Introduction to web.xml configuration of each node:
Specify a filter. Used to specify a name for the filter, and the content of the element cannot be empty. Element is used to specify the fully qualified class name of the filter. The element is used to specify initialization parameters for the filter, and its child elements specify the name of the parameter and the value of the parameter. In the filter, you can use the FilterConfig interface object to access the initialization parameters. Element is used to set the resource that a Filter is responsible for intercepting. A resource intercepted by a Filter can be specified in two ways: the Servlet name and the request path child element of the resource access is used to set the registered name of the filter. This value must be the name of the filter declared in the element. Set the request path intercepted by filter (the URL style associated with the filter) that specifies the Servlet name intercepted by the filter. Specifies how the resource intercepted by the filter is called by the Servlet container, which can be one of REQUEST,INCLUDE,FORWARD and ERROR, and the default REQUEST. Users can set multiple child elements to specify multiple ways for Filter to intercept calls to resources. The value that the child element can set and its meaning REQUEST: when the user accesses the page directly, the Web container will call the filter. If the target resource is accessed through the include () or forward () method of RequestDispatcher, the filter will not be called. INCLUDE: this filter will be called if the target resource is accessed through the include () method of RequestDispatcher. Otherwise, the filter will not be called. FORWARD: if the target resource is accessed through the forward () method of RequestDispatcher, then the filter will be called, otherwise, the filter will not be called. ERROR: this filter will be called if the target resource is called through a declarative exception handling mechanism. Otherwise, the filter will not be called.
Filter chain
In a web application, multiple Filter can be developed and written, and the combination of these Filter is called a Filter chain.
The web server decides which Filter to call first according to the order in which Filter is registered in the web.xml file. When the doFilter method of the first Filter is called, the web server creates a FilterChain object that represents the Filter chain and passes it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server checks to see if there is any filter in the FilterChain object, and if so, calls the second filter, and if not, the target resource.
Life cycle of Filter
Public void init (FilterConfig filterConfig) throws ServletException;// initialization
Like the Servlet program we wrote, the WEB server is responsible for the creation and destruction of the Filter. When the web application starts, the web server will create an instance object of Filter, call its init method, read the web.xml configuration, and complete the initialization of the object, thus preparing for the interception of subsequent user requests (the filter object will only be created once, and the init method will only be executed once). Developers can obtain a FilterConfig object that represents the current filter configuration information through the parameters of the init method.
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;// intercepts requests
This method completes the actual filtering operation. When a customer requests access to the URL associated with the filter, the Servlet filter executes the doFilter method first. The FilterChain parameter is used to access subsequent filters.
Public void destroy (); / / destroy
The Filter object resides in memory after it is created and is destroyed when the web application is removed or the server stops. Called before the Web container unloads the Filter object. This method is executed only once in the life cycle of the Filter. In this method, you can release the resources used by the filter.
FilterConfig interface
When you configure filter, you can configure some initialization parameters for filter. When the web container instantiates the Filter object and calls its init method, it will pass in the filterConfig object that encapsulates the filter initialization parameters. Therefore, when writing filter, developers can obtain the following through the methods of the filterConfig object:
String getFilterName (); / / gets the name of the filter. String getInitParameter (String name); / / returns the value of the initialization parameter with the name specified in the deployment description. Returns null if it does not exist. Enumeration getInitParameterNames (); / / returns an enumerated collection of the names of all initialization parameters of the filter. Public ServletContext getServletContext (); / / returns a reference to the Servlet context object.
Filter use case
Use Filter to verify user login security control
Some time ago to participate in the maintenance of a project, users quit the system, and then go to the address bar to access the history, according to url, can still enter the system response page. I went to check and found that the request was not filtered to authenticate the user login. Add a filter to solve the problem!
Configure it in web.xml first
SessionFiltercom.action.login.SessionFilterlogonStrings/project/index.jsp;login.doincludeStrings.do;.jspredirectPath/index.jspdisabletestfilterNSessionFilter/*
Then write FilterServlet.java:
Package com.action.login;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;import javax.servlet.http.HttpServletResponseWrapper;/*** determines whether the user is logged in. If you do not log in, log out of the system * / public class SessionFilter implements Filter {public FilterConfig config;public void destroy () {this.config = null } public static boolean isContains (String container, String [] regx) {boolean result = false;for (int I = 0; I < regx.length; iTunes +) {if (container.indexOf (regx [I])! =-1) {return true;}} return result;} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest hrequest = (HttpServletRequest) request;HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper ((HttpServletResponse) response); String logonStrings = config.getInitParameter ("logonStrings") / / login page String includeStrings = config.getInitParameter ("includeStrings"); / / filter resource suffix parameter String redirectPath = hrequest.getContextPath () + config.getInitParameter ("redirectPath"); / / No login redirection page String disabletestfilter = config.getInitParameter ("disabletestfilter"); / / whether the filter is valid if (disabletestfilter.toUpperCase (). Equals ("Y")) {/ / filter invalid chain.doFilter (request, response); return } String [] logonList = logonStrings.split (";"); String [] includeList = includeStrings.split (";"); if (! this.isContains (hrequest.getRequestURI (), includeList)) {/ / filter only the specified filter parameter suffix chain.doFilter (request, response); return;} if (this.isContains (hrequest.getRequestURI (), logonList)) {/ / A pair of login pages do not filter chain.doFilter (request, response); return } String user = (String) hrequest.getSession (). GetAttribute ("useronly"); / / determine whether the user logs in to if (user = = null) {wrapper.sendRedirect (redirectPath); return;} else {chain.doFilter (request, response); return;}} public void init (FilterConfig filterConfig) throws ServletException {config = filterConfig;}}
In this way, all requests to the user can be completed, and the user login must be verified through this Filter.
Filter to prevent Chinese garbled code
When the project uses the spring framework. This filter can be used when different character sets are used in the foreground JSP page and JAVA code to encode data submitted by the form or garbled in uploading / downloading Chinese name files.
Encodingorg.springframework.web.filter.CharacterEncodingFilterencodingUTF-8forceEncodingfalseencoding/*
The OpenSessionInViewFilter of Spring+Hibernate controls the switch of session
When hibernate+spring is used together, if lazy=true (delayed loading) is set, hibernate will automatically close session when reading data, after reading parent data, so that when you want to use the associated data and child data, the system will throw an error of lazyinit. In this case, you need to use the OpenSessionInViewFilter filter provided by spring.
OpenSessionInViewFilter mainly maintains the Session state until request sends all the pages to the client, and does not close session until the end of the request, which can solve the problem caused by delayed loading.
Note: the OpenSessionInViewFilter configuration should be written before the configuration of the struts2. Because the tomcat container loads the filter in order, if the configuration file first writes the filter configuration of struts2, then the filter configuration of OpenSessionInViewFilter, the order of loading results in that session is not managed by spring when action gets the data.
OpenSessionInViewFilterorg.springframework.orm.hibernate3.support.OpenSessionInViewFiltersessionFactoryBeanNamesessionFactorysingleSessiontrueOpenSessionInViewFilter*.do
Web.xml configuration of Struts2
Using Struts2 in the project also needs to configure a filter in web.xml to intercept the request and transfer it to the Action of Struts2 for processing.
Note: if you are in a version of Struts2 prior to 2.1.3, the filter uses org.apache.struts2.dispatcher.FilterDispatcher. Otherwise, use org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter. Starting with Struts2.1.3, the ActionContextCleanUp filter is discarded and the corresponding functionality is included in the StrutsPrepareAndExecuteFilter filter.
Configuration of three initialization parameters:
Config parameter: specifies the configuration file to load. Comma division. The actionPackages parameter: specifies the package space where the Action class resides. Comma division. ConfigProviders parameter: custom profile provider, which needs to implement the ConfigurationProvider interface class. Comma division.
Struts2org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterstruts2*.do
At this point, I believe you have a deeper understanding of "what is the function of Filter in Java?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.