Filter
The filter is used to filter the resources accessed by the client. If it meets the conditions, it will be released. If it does not meet the conditions, it will not be released. In addition, it can carry out logical processing before and after the access of the target resources.
Steps:
- Write a Filter class to implement the Filter interface
- Implement the methods not yet implemented in the interface (focus on implementing the doFilter method)
- Configure in web.xml (mainly configure which resources to filter)
Example: filter implementation class:
package com.yyb.filter; import java.io.IOException; import javax.servlet.*; /** * Created by Administrator on 2017/7/28. */ public class FilterDemo implements Filter { @Override //The init method is executed when the Filter is created public void init(FilterConfig filterConfig) throws ServletException { //1. Get the name of the filter in web.xml < filter name > filterdemo < / filter name > System.out.println(filterConfig.getFilterName()); //2. Get the initialization parameters of the current filter System.out.println(filterConfig.getInitParameter("aaa")); //3. Get servletContext filterConfig.getServletContext(); System.out.println("init ...."); } @Override //doFilter is the core filtering method of Filter /* * request: The internal encapsulation is the content of the client http request * response: Represents a response * FilterChain: Filter chain object */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("quick1 running...."); //Release request chain.doFilter(request, response); } @Override //Execute the destroy method when the Filter object is destroyed public void destroy() { System.out.println("destroy..."); } }
web.xml
<filter> <filter-name>FilterDemo</filter-name> <filter-class>com.yyb.filter.FilterDemo</filter-class> </filter> <filter-mapping> <filter-name>FilterDemo</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
API details of Filter
Filter life cycle and its life cycle related methods. The filter interface has three methods, and these three methods are all related to the life of filter:
- init(Filterconfig): represents the initialization method of the filter object, which is executed when the filter object is created.
- doFilter(ServletRequest,ServletResponse,FilterCha): the core method of filtering on behalf of the filter. If a resource has been configured to this filter for filtering, the doFilter method will be executed every time the resource is accessed.
- Destruction (): represents the filter destruction method, which is executed when the filter object is destroyed.
Lifecycle of Filter object
- When filter is created: the filter object is created when the server starts
- When to destroy the filter: the filter is destroyed when the server is shut down
init(FilterConfig): where the parameter config represents the configuration information of the filter object, and the internal encapsulation is the configuration information of the filter.
Destruction () method: executed when the filter object is destroyed.
doFilter method: doFilter(ServletRequest,ServletResponse,FilterChain). The parameter ServletRequest/ServletResponse is that each time the doFilter method is executed, the web container is responsible for creating a request and a response object to pass in as the parameters of doFilter. The request and response are the request and response when accessing the service method of the target resource. FilterChain is a filter chain object whose doFilter method can release the request. The chain object executes the filter in turn according to the configured filter mapping order.
<filter> <filter-name>FilterDemo</filter-name> <filter-class>com.yyb.filter.FilterDemo</filter-class> </filter> <filter-mapping> <filter-name>FilterDemo</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
URL pattern configuration
-
perfect match
/ Servlet1, which is executed only when Servlet1 is accessed -
Directory matching / aaa/bbb/*
/user /: access the foreground resources to enter this filter
/admin /: this filter is executed when accessing resources in the background -
Extension matches *. abc *.jsp
Note: URL pattern can be replaced by servlet name or mixed.
<filter-mapping> <filter-name>FilterDemo</filter-name> <!--<url-pattern>/*</url-pattern>--> <servlet-name>FilterTest</servlet-name> <servlet-name>FilterTest1</servlet-name> </filter-mapping>
dispatcher: access method
- REQUEST: the default value, which means that the filter is executed when a resource is accessed directly
- FORWARD: filter is executed only when forwarding
- INCLUDE: execute filter when containing resources
- ERROR: execute filter when jump occurs
Example: web.xml
<filter> <filter-name>FilterDemo</filter-name> <filter-class>com.yyb.filter.FilterDemo</filter-class> </filter> <filter-mapping> <filter-name>FilterDemo</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping>
In FilterTest, add the forwarding code request.getRequestDispatcher("/index.jsp").forward(request, response), At this point, when you access FilterTest, the filter will only execute sequentially, not twice. Filters are not executed when forwarding.
However, the redirection will be executed twice. In FilterTest, add the forwarding code response.sendRedirect(request.getContextPath()+"/index.jsp"), You can see the execution results.
Function of Filter
- Extraction of common code
- Methods in request and response can be enhanced (decorator mode / dynamic proxy)
- Perform permission control
Using filter to solve parameter Chinese garbled code
package com.ithiema.web.filter; import java.io.IOException; import java.io.UnsupportedEncodingException; 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.HttpServletRequestWrapper; public class EncodingFilter implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //request.setCharacterEncoding("UTF-8"); //Enhance the getParameter method of the request before passing the request /* * Decorator mode (packaging) * * 1,The enhanced class and the enhanced class should implement a unified interface * 2,Pass in the enhanced class * 3,Method overrides that need to be enhanced and method calls that do not need to be enhanced * */ //Enhanced object HttpServletRequest req = (HttpServletRequest) request; //Enhanced object EnhanceRequest enhanceRequest = new EnhanceRequest(req); chain.doFilter(enhanceRequest, response); } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } } class EnhanceRequest extends HttpServletRequestWrapper{ private HttpServletRequest request; public EnhanceRequest(HttpServletRequest request) { super(request); this.request = request; } //Enhancement of getparameter @Override public String getParameter(String name) { String parameter = request.getParameter(name);//Garbled code try { parameter = new String(parameter.getBytes("iso8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return parameter; } }