introduce
- The filter comes from an interface in the Servlet specification
- The filter interface can intercept the request before it reaches the target resource file, so that it can judge whether the request is legitimate or enhance the interception request.
- The filter interface implementation class needs to be implemented by the developer
Filter implementation steps
- Create an implementation class for the filter interface
- Rewrite the doFilter method in the interface to judge the validity of intercepted requests or to enhance the processing of intercepted requests
- Register filters in web.xml
- Let tomcat be responsible for creating filter objects at tomcat startup
- Notify tomcat which requests will be intercepted by the filter
Small case realizes judging the validity of requests through filters
Create a new web project
As mentioned above, the filter intercepts the entry before the request reaches the target resource file. For simplicity, we store an image under the web directory. The results of the new web project directory are as follows:
New Class Implementing Filter Interface
import javax.servlet.*; import java.io.IOException; public class OneFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override /** * servletRequest:Request object * servletResponse:Request return object * filterChain: Filter Chain Object */ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String age = servletRequest.getParameter("age"); if (Integer.valueOf(age) >= 18) { // Request legality, release filterChain.doFilter(servletRequest, servletResponse); } else { // Termination request servletResponse.setCharacterEncoding("GBK"); servletResponse.getWriter().write("Come back in two years"); } } @Override public void destroy() { } }
The main override in the filter class is the doFilter method, which can intercept or release requests. For example, when we request image resources, we need to pass an age parameter. If we are older than 18 years old, the request is legitimate. Otherwise, it is illegal. Here, if we release, we use filt. ErChain. doFilter (request, response); method for release.
Configure filters in web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <filter> <filter-name>OneFileter</filter-name> <filter-class>OneFilter</filter-class> </filter> <filter-mapping> <filter-name>OneFileter</filter-name> <!--This means that as long as the request path is.jpg All that ends with entry interception--> <url-pattern>*.jpg</url-pattern> </filter-mapping> </web-app>
The url-pattern tag here matches the request address. See the specific matching method. Serlet Foundation This article.
Request testing
Deploy the project to tomcat and enter the address after startup http://localhost:8080/myWeb/timg.jpg?age=24 Access allows access to image resources, if input http://localhost:8080/myWeb/timg.jpg?age=12 Then the word'Come back in two years'will appear.
Small Case Implementation Filter Enhances Interception Request
The case here is to use filters to enhance the entry of interception requests, as well as to create a new web project and write two servlet s
The first servlet
package top.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "Servlet") public class OneServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request.setCharacterEncoding("utf-8"); String uname = request.getParameter("uname"); System.out.println("one" + uname); } }
The second servlet
package top.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "Servlet2") public class TwoServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request.setCharacterEncoding("utf-8"); String uname = request.getParameter("uname"); System.out.println("two" + uname); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>OneServlet</servlet-name> <servlet-class>top.servlet.OneServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OneServlet</servlet-name> <url-pattern>/one.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>TwoServlet</servlet-name> <servlet-class>top.servlet.TwoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TwoServlet</servlet-name> <url-pattern>/two.do</url-pattern> </servlet-mapping> </web-app>
jsp
<%-- Created by IntelliJ IDEA. User: lg Date: 2019/7/30 Time: 22:11 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="/myWeb/one.do" method="post"> Parameters:<input type="text" name="uname"> <input type="submit" value="OneServlet"> </form> <form action="/myWeb/two.do" method="post"> Parameters:<input type="text" name="uname"> <input type="submit" value="TwoServlet"> </form> </body> </html>
Page effect
Access effects
You can see that the Chinese scrambling code is used when post s are submitted, and a code request.setCharacterEncoding("utf-8") is annotated in the servlet; this code can solve the problem of Chinese scrambling, but if there are many servlets, each of them is added in this way, the cost of maintenance is relatively high, and it can pass through at this time. Through the filter to achieve this function, you can see that the request path of the two servlets conforms to the form of the suffix of. do, using filter input to enhance the request ending with. do.
Create filters
package top.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; @WebFilter(filterName = "Filter") public class OneFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { // Enhance requests req.setCharacterEncoding("utf-8"); // Request for release chain.doFilter(req, resp); } public void init(FilterConfig config) throws ServletException { } }
web.xml configuration filter
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>OneServlet</servlet-name> <servlet-class>top.servlet.OneServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OneServlet</servlet-name> <url-pattern>/one.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>TwoServlet</servlet-name> <servlet-class>top.servlet.TwoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TwoServlet</servlet-name> <url-pattern>/two.do</url-pattern> </servlet-mapping> <filter> <filter-name>OneFilter</filter-name> <filter-class>top.filter.OneFilter</filter-class> </filter> <filter-mapping> <filter-name>OneFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> </web-app>
At this time, the problem of Chinese scrambling has been solved.
FilterChain interface
- The implementation class of the FilterChain interface is provided by tomcat
- FilterChain is essentially an array
- All filter objects that intercept this request are stored in the array
- The filter chain object is equivalent to a schedule to decide which filter to execute first
Filter is to intercept or enhance requests, in fact, the same request can be configured with multiple filters, each filter has different functions, so when multiple filters intercept the same request entry, which filter is executed first and which one is executed later, which filter is actually configured with web.xml. The <filter-mapping> </filter-mapping> label of the filter is related, and the <filter-mapping> </filter-mapping> label is executed first.