The difference and connection between filter and servlet

Source: Internet
Author: User

Filter Introduction

Filter can be considered as a "variant" of the servlet, which is mainly used to preprocess user requests or post-process httpservletresponse, which is a typical processing chain. It differs from the servlet in that it cannot generate a response directly to the user. The complete process is that thefilter pre-processes the user request, then gives the request to the servlet for processing and generates a response, and finally the filter then processes the server response.

Filter has several uses.

    • Intercept the client's httpservletrequest before HttpServletRequest arrives at the servlet.
    • You can also modify the HttpServletRequest header and data as needed to check the httpservletrequest.
    • Intercept HttpServletResponse before HttpServletResponse arrives at the client.
    • You can also modify the HttpServletResponse header and data as needed to check the httpservletresponse.

There are several types of filter.

    • User-Authorized Filter:filter is responsible for checking the user request and filtering the user's illegal request according to the request.
    • Log filter: Records some special user requests in detail.
    • Filter that is responsible for decoding: Includes request decoding for non-standard encoding.
    • XSLT filter that can change XML content.
    • Filter is responsible for intercepting multiple requests or responses, and one request or response can be intercepted by multiple requests.

Creating a filter takes only two steps:

    • Building filter processing class;
    • Config filter in the Web. xml file.

The following is a simple log filter, which intercepts all user requests and logs the requested information.

Codepublic class Logfilter implements Filter
{
Filterconfig configuration information that can be used to access the filter
Private Filterconfig config;
Implementing the Initialization method
public void init (filterconfig config)
{
this.config = config;
}
Implementing the Destruction method
public void Destroy ()
{
This.config = null;
}
Core methods for performing filtering
public void DoFilter (servletrequest request,servletresponse response, Filterchain chain) throws IOException, Servletexception
{
---------The following code is used to perform preprocessing on user requests---------
Get the ServletContext object for logging
ServletContext context = This.config.getServletContext ();
Long before = System.currenttimemillis ();
System.out.println ("Start filtering ...");
Convert requests to httpservletrequest requests
HttpServletRequest hrequest = (httpservletrequest) request;
Record log
Context.log ("Filter has intercepted the user's request address:" + hrequest.getservletpath ());
Filter is only chained, and requests are still released to the destination address.
Chain.dofilter (request, response);
---------The following code is used to perform post-processing on the server response---------
long after = System.currenttimemillis ();
Record log
Context.log ("Filter End");
Record the log again
Context.log ("request is located to" + Hrequest.getrequesturi () + "time Spent:" + (After-before));
}
}

The above program implements the DoFilter () method, the implementation of the method can be implemented to pre-processing the user request, can also be implemented after the server response-their demarcation line is whether to call the Chain.dofilter (), before executing the method, that is, the user request preprocessing After the method is executed, the server response is post-processed.

In the above request filter, only the requested URL is recorded in the log, the Chain.dofilter (request,reponse) method is executed for all requests, and when filter is filtered on the request, the request is still sent to the destination address. If you need to check permissions, you can determine whether the user's permissions are sufficient in the filter based on the httpsession requested by the user. If you have insufficient permissions, you can call redirect directly without calling the Chain.dofilter (Request,reponse) method.

Code ================== Firstfilter.java
==================
Package com.test.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;

public class Firstfilter implements Filter {

@Override
public void Destroy () {

}

@Override
public void DoFilter (ServletRequest request, servletresponse response,
Filterchain chain) throws IOException, Servletexception {
System.out.println ("Before Invoke Firstfilter ' s chain.dofilter ():");
Chain.dofilter (request, response);
System.out.println ("After invoke Firstfilter ' s chain.dofilter ():");
}

@Override
public void init (Filterconfig arg0) throws Servletexception {
System.out.println ("Firstfilter init () ..."); } }

============
Secondfilter.java
=============

Package com.test.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;

public class Secondfilter implements Filter {

@Override
public void Destroy () {

}

@Override
public void DoFilter (ServletRequest request, servletresponse response,
Filterchain chain) throws IOException, Servletexception {
System.out.println ("Before Invoke Secondfilter ' s chain.dofilter ():");
Chain.dofilter (request, response);
System.out.println ("After invoke Secondfilter ' s chain.dofilter ():");
}

@Override
public void init (Filterconfig filterconfig) throws Servletexception {
System.out.println ("Secondfilter init () ...");
}}
==========
Firstservlet.java
==========
Package com.test.servlet;

Import java.io.IOException;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Firstservlet extends HttpServlet {

@Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
System.out.println ("servlet doget be invoked ...");
Req.getrequestdispatcher ("test.jsp"). Forward (req, resp);
}

@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
TODO auto-generated Method Stub
Doget (req, resp);
} }

Web. XML

Code
<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>firstFilter</filter-name>
<filter-class>com.test.filter.FirstFilter</filter-class>
</filter>
<filter>
<filter-name>secondFilter</filter-name>
<filter-class>com.test.filter.SecondFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>secondFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>firstFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>firstServlet</servlet-name>
<servlet-class>com.alimama.servlet.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>firstServlet</servlet-name>
<url-pattern>/firstServlet</url-pattern>
</servlet-mapping>
</web-app>

Then publish, find the printed log as follows:

。。。

Firstfilter init () ...
Secondfilter init () ...

。。。
Info: Server Startup in 3665 MS

Here the filter is initialized well.

When we visit our application:http://127.0.0.1:8080/appName

Find the print journal as follows:

Before invoke Secondfilter ' s chain.dofilter ().
Before invoke Firstfilter ' s chain.dofilter ().
After invoke Firstfilter ' s chain.dofilter ():
After invoke Secondfilter ' s chain.dofilter ():

When we adjust the position of the filter in Web. XML (Note the order of filter-mapping):

Code<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>firstFilter</filter-name>
<filter-class>com.test.filter.FirstFilter</filter-class>
</filter>
<filter>
<filter-name>secondFilter</filter-name>
<filter-class>com.test.filter.SecondFilter</filter-class>
</filter>
<span style= "COLOR: #ff0000" > <filter-mapping>
<filter-name>firstFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>secondFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping></SPAN>

<servlet>
<servlet-name>firstServlet</servlet-name>
<servlet-class>com.alimama.servlet.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>firstServlet</servlet-name>
<url-pattern>/firstServlet</url-pattern>
</servlet-mapping>
</web-app>

Then, when you start the app, you'll see the print:

Before invoke Firstfilter ' s chain.dofilter ().

Before invoke Secondfilter ' s chain.dofilter ().
After invoke Secondfilter ' s chain.dofilter ():

After invoke Firstfilter ' s chain.dofilter ():

Here is an example:

Code

In the Dofilter method above filter 3 lines of italic code to get the filter configuration parameters, and the program in bold code is the core of this filter, ① code according to the configuration parameters set the request code to use the character set, The following bold code determines if there is a user attribute in the session range-No such attribute is assumed to be not logged in, and if neither is logged in and the request address is not a login page and the login page is processed, the system jumps directly to the login page.

Configuring the filter in the Web. xml file, using the Init-param element to configure the parameter for the filter, Init-param accepts the following two child elements:

Param-name: Specifies the name of the parameter.

Param-value: Specifies the parameter value.

The configuration snippet for this filter is as follows:

Code

The bold code in the configuration fragment above specifies 3 configuration parameters for the filter, specifying LoginPage to/login.jsp,prologin as/prologin.jsp, which indicates that if the app is not logged in, ordinary users can only access/login.jsp and/ Prologin.jsp page. Users are free to access other pages only after they have logged in to the app.

In fact, the filter is very similar to the servlet, except that filter cannot generate a response directly to the user. In fact, the code in the filter Dofilter () method is the generic code drawn from the service () method of multiple Servlets, which allows for better reuse by using the filter.

Listener, filter, servlet loading order and its explanation in Web. xml

In the project there will always be some problems about the priority of the load, just encountered a problem, because the project using the Quartz Task Scheduler, quartz in Web. XML is using listener for monitoring, Allows the database to be checked immediately when Tomcat is started to see those tasks not being executed on time, The configuration information for the database is configured with the servlet in Web. XML, causing Tomcat to execute the quartz task times null pointer after the boot, because the database connection information in the servlet is not loaded. On-line query the load priority of the configuration in Web. xml:

The first thing to be sure is that the order of loading is independent of their order in the Web. xml file. That is, the filter is not loaded before the filter is written in front of the listener. The final conclusion is:listener, filter, servlet

There is also a configuration section: Context-param, which is used to provide ServletContext with key-value pairs, which are application context information. Our listener, filter, and so on are initialized with the information in these contexts, so should the Context-param configuration section be written before the Listener configuration section? In fact, the Context-param configuration section can be written anywhere, so the real load order is: Context-param, listener, filter, servlet

For a class of configuration sections, it is related to the order in which they appear. In the case of filter, it is possible to define multiple filter in Web. XML, a configuration section related to filter is filter-mapping, and it is important to note that for filter and filter-mappin with the same filter-name In the case of the G configuration section, the filter-mapping must appear after the filter, or the corresponding filter-name is undefined when parsing to filter-mapping. When each filter is initialized when the Web container starts, it is initialized in the order in which the Filter configuration section appears, and when the request resource matches multiple filter-mapping, thefilter intercept resource is in accordance with the filter-mapping The configuration section appears in order to call the DoFilter () method in turn.

The servlet is similar to filter and is not mentioned here.

From this, it can be seen that the loading order of Web. XML is: Context-param, Listener, filter -a servlet, and the order of the actual program calls between the same types is called according to the Order of the corresponding mapping.

The difference and connection between filter and servlet

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.