Filter Filter output HelloFilter

Filter filter is used to filter requests and responses Servlet, the following shows a map for

Let's write the first Filter, Filter in fact very similar to Servlet, Filter also interfaces, in writing Filter time, but also inside doFilter method overrides, and to intercept through the configuration file or annotations by implementing the Filter interface, which files can write a note here about, when rewriting Filter method requires the release operation requests and responses to pass, be good examples.

First we write a class that implements the Filter interface, here is first implemented xml configuration file, Filter is javax.servlet package

package com.zhiying.filter;

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

public class FilterDemo1 implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Hello Filter");

        //放行
        chain.doFilter(request,response);
    }
}

Then we simply modify the index.jsp file for testing


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  index.jsp...
  </body>
</html>

The final step is 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>demo1</filter-name>
        <filter-class>com.zhiying.filter.FilterDemo1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>demo1</filter-name>
<!--        这里的意思是执行所有的方法都会通过该过滤器,也就是拦截路径-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 As can be seen from the figure, but when we visited index.jsp, the output of Hello Filter, which is performed Filter filter 

If we use notes, then, will be more simple, just a @WebFilter ()

package com.zhiying.filter;

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

@WebFilter("/*") //这里的意思是执行所有的方法都会通过该过滤器,也就是拦截路径
public class FilterDemo1 implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Hello Filter");

        //放行
        chain.doFilter(request,response);
    }
}

web.xml file is not configured, to get a comment, the above results can be obtained.

Published 370 original articles · won praise 242 · views 50000 +

Guess you like

Origin blog.csdn.net/HeZhiYing_/article/details/104055776