Create a filter that intercepts all requests

 

Project structure:

 

 

 

Is AFilter:

package cn.itcast.web.filter;

import javax.servlet.*;
import java.io.IOException;

public class AFilter implements Filter {
    /** * Init method is performed immediately after the filter is created, used for initialization
     * @param filterConfig
     * @throws ServletException
     */
    @Override void the init public (the FilterConfig FilterConfig) throws ServletException {System.out.println ( "Filter Initialization!" );} / * ** performed every time the filter * @param servletRequest * @param servletResponse * @param filterChain * @throws ServletException * * @throws IOException / @Override the doFilter public void (the servletRequest servletRequest, the ServletResponse ServletResponse, the filterChain filterChain) throws IOException, ServletException {System.out.println ( "filter knockdown ..." ); the FilterChain.doFilter (servletRequest, ServletResponse ); System.out.println ( "back execution doFilter method ..." ); } / * ** the destroy method before performing destruction, for releasing * / non-memory resources @Override public void the destroy () {the System. Out.println ( "filter destruction!" );}}

 

web.xml Configuration

<?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_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>AServlet</servlet-name>
        <servlet-class>cn.itcast.web.servlet.AServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AServlet</servlet-name>
        <url-pattern>/AServlet</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>AFilter</filter-name>
        <filter-class>cn.itcast.web.filter.AFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>AFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 index.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%System.out.println("执行index.jsp。。。");%>
    index.jsp page
</body>
</html>

 

 Console output:

Init method of execution start of the project

 访问index.jsp,http://localhost:8080/day09/index.jsp

 DoFilter execution method

 

 Shut down the server Destruction filter

 

Will destroy method is called before destroying filter

 

Guess you like

Origin www.cnblogs.com/gongwy/p/11870544.html