Servlet filter, servlet

Source: Internet
Author: User

Servlet filter, servlet

I,FilterIntroduction and use

What is a filter?

Similar to Servlet, a filter is a web application component that can be bound to a web application. However, unlike other web application components, filters are "Links" in container processing. This means that they will access an incoming request before the servlet processor and access the response information before sending the response information to the customer. This access allows the filter to check and modify the content of the request and response.

Where does the filter apply?

L create a model for new features of a web application (can be added to or removed from a web application without rewriting the code of the grassroots application );

L add new features to previous code.

Where is the filter placed in the container structure?

Before placing a filter on a web resource, you can intercept the access request before the request reaches the web resource of the application (a Servlet, a Jsp page, or even an HTML page, and the output request is intercepted before it returns to the customer. Filter: Used to intercept requests. It is between the client and the requested resource and is used to reuse code. Filter chain, which is configured first in web. xml and called first. You can also configure initialization parameters in the filter.

The Filter in Java is not a standard Servlet. It cannot process user requests or generate responses to clients. It is mainly used to pre-process HttpServletRequest or HttpServletResponse. It is a typical processing chain.

Filters are useful in the following ways:

L intercept the customer's HttpServletRequest before HttpServletRequest arrives at the Servlet.

L check HttpServletRequest as needed, or modify the HttpServletRequest header and data.

L intercept HttpServletResponse before HttpServletResponse arrives at the client.

L check HttpServletResponse as needed. You can modify the HttpServletResponse header and data.

Filter has the following types:

L user-authorized Filter: The Filter checks user requests and filters illegal user requests according to requests.

L LOG Filter: records some special user requests in detail.

L Filter responsible for decoding: including decoding requests for non-standard encoding.

L it can change the tfilter of XML content.

A Filter can intercept multiple requests or responses: one request or response can also be intercepted by multiple requests.

Two steps are required to create a Filter:
(1) create a Filter processing class:

(2) Configure Filter in the web. xml file.
To create a Filter, you must implement the javax. servlet. Filter interface, which defines three methods.
• Void init (FilterConfig config): used to initialize the Filter.
• Void destroy (): Used to recycle certain resources before the Filter is destroyed.
• Void doFilter (ServletRequest request, ServletResponse response, FilterChain chain): implements the filter function. This method is used to add additional processing for each request and response.

The Filter also has a lifecycle: init ()-> doFilter ()-> destroy (), which is driven by the filter element in the deployment file. In servlet2.4, the filter can also be used to request the dispatcher, but must be in the web. the <dispatcher> INCLUDE, FORWARD, REQUEST, or ERROR </dispatcher> element is in filter-mapping.

Common Filter scenarios:

One instance

First, let's take a look at the web. xml configuration:

   

<! -- Request url logging filter --> <filter-name> logfilter </filter-name> <filter-class> com. weijia. filterservlet. logFilter </filter-class> </filter> <filter-mapping> <filter-name> logfilter </filter-name> <url-pattern>/* </url-pattern> </filter-mapping> <! -- Encoding filter --> <filter-name> setCharacterEncoding </filter-name> <filter-class> com. weijia. filterservlet. encodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> </filter> <filter-mapping> <filter-name> setCharacterEncoding </filter-name> <url-pattern>/* </url-pattern> </filter- mapping>

 

Then let's take a look at the encoding filter:

Package com. weijia. filterservlet; import java. io. IOException; import java. util. enumeration; import java. util. hashMap; 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 EncodingFilter implements Filter {private String encoding; Private HashMap <String, String> params = new HashMap <String, String> (); // The public void destroy () {System. out. println ("end do the encoding filter! "); Params = null; encoding = null;} public void doFilter (ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {System. out. println ("before encoding" + encoding + "filter! "); Req. setCharacterEncoding (encoding); chain. doFilter (req, resp); System. out. println (" after encoding "+ encoding +" filter! "); System. err. println ("--------------------------------------");} // The public void init (FilterConfig config) throws ServletException {System is read at project startup. out. println ("begin do the encoding filter! "); Encoding = config. getInitParameter (" encoding "); for (Enumeration <?> E = config. getInitParameterNames (); e. hasMoreElements ();) {String name = (String) e. nextElement (); String value = config. getInitParameter (name); params. put (name, value );}}}

 


LOG filter:

Package com. weijia. filterservlet; 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; public class LogFilter implements Filter {public FilterConfig config; public voi D destroy () {this. config = null; System. out. println ("end do the logging filter! ");} Public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {System. out. println (" before the log filter! "); // Convert the request to HttpServletRequest request HttpServletRequest hreq = (HttpServletRequest) req; // record the log System. out. println ("Log Filter has intercepted the user's request address:" + hreq. getServletPath (); try {// Filter is only chained and the request is still forwarded to the destination address. Chain. doFilter (req, res);} catch (Exception e) {e. printStackTrace ();} System. out. println ("after the log filter! ");} Public void init (FilterConfig config) throws ServletException {System. out. println (" begin do the log filter! "); This. config = config ;}}

 


Test Servlet:

package com.weijia.filterservlet;    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 FilterServlet extends HttpServlet {        private static final long serialVersionUID = 1L;        public void doGet(HttpServletRequest request, HttpServletResponse response)              throws ServletException, IOException {          response.setDateHeader("expires", -1);      }        public void doPost(HttpServletRequest request, HttpServletResponse response)              throws ServletException, IOException {      }    }  

Access FilterServlet

Running result:

Before the log filter!
Log Filter has intercepted the user's request address:/FilterServlet
Before encoding UTF-8 filter!
After encoding UTF-8 filter!
----------------------------------------
After the log filter!


We can see the call relationship of this filter from the running result:

Similar to the calling sequence of constructor and destructor in C ++,

Here we register the LOG filter in web. xml before registering

 

When we redeploy the application, we find that:

Will first destroy the last filter, and then re-register it

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.