background

CatFilter is used for HTTP monitoring, that is, monitoring methods in the Controller class of a Web project.

The implementation principle is actually the filter in the servlet.

This article focuses on how to implement monitoring URL monitoring for Springboot Web projects and non-Springboot Web projects.

CatFilter

Is a cat client JAR class that implements the Filter interface in servlets.

Non-springboot Web projects

You can configure the filter directly. After configuring the filter, it is equivalent to introducing the filter. This method is the same as servlet filter.


web.xml

<! -- cat monitoring HTTP requests --> <filter> <filter-name>cat-filter</filter-name> <filter-class>com.dianping.cat.servlet.CatFilter</filter-class> </filter> <filter-mapping> <filter-name>cat-filter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>Copy the code

Springboob web project

To intercept all requests, use the CatFilter that comes with CAT.

However, if you want to exclude static resources, you need to extend CatFilter, because springBoot Filter does not support excluding resource paths and only supports pattern matching.

Extension CatFilter

package com.xxx.qrcode.ugate.payment.filter; import com.dianping.cat.servlet.CatFilter; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.util.AntPathMatcher; /** * override CatFilter, .js/.css/.html * * @author GZH * @createTime 2021/2/23 2:54pm */ Public class QrcodeCatFilter extends CatFilter Private static List<String> excludeUrlPatterns = array.asList ("/**/*.html", "/**/*.jsp", "/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg", "/**/*.gif", "/**/*.svg"); private static AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// Obtain the relative path of the current request (i.e. the path after removing the domain name/project name) HttpServletRequest HttpServletRequest = (HttpServletRequest)request; String ServletPath = httpServletRequest.getServletPath(); / / check whether the path matching Boolean b = excludeUrlPatterns. Stream () anyMatch (e - > antPathMatcher. Match (e, ServletPath)); If (b) {// If the resource is static, do not go CatFilter chain. DoFilter (request, response); }else {CatFilter super.dofilter (request, response, chain); }}}Copy the code

1. The custom extension class, which overwrites the interception method doFilter, will decide whether to be intercepted based on whether it is a static resource request path.

2. On startup, methods such as CatFilter init will still be executed because the custom extension class inherits CatFilter.

Configuring filters

Configuring filters

/** * public FilterRegistrationBean registerFilter() {FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new QrcodeCatFilter()); // registration.addUrlPatterns("*.do"); // registration.addInitParameter("exclusions", "*.css"); // registration.setName("CatFilter"); return registration; }Copy the code

Complete configuration

package com.xxx.xxx.ugate.payment.config.webconfig; import com.xxx.qrcode.ugate.payment.filter.QrcodeCatFilter; import com.xxx.qrcode.ugate.payment.intercepter.LogPreInterceptor; import xxx.log.logback.web.LogbackConfigListener; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * LogbackConfigListener Configures a log file */ @configuration public class WebConfig implements WebMvcConfigurer {@bean public ServletListenerRegistrationBean<LogbackConfigListener> initLogbackConfigListener() { ServletListenerRegistrationBean<LogbackConfigListener> result = new ServletListenerRegistrationBean<>(); result.setListener(new LogbackConfigListener()); return result; Public void addInterceptors(InterceptorRegistry) {/** * public void addInterceptors(InterceptorRegistry) { registry.addInterceptor(new LogPreInterceptor()) // .addPathPatterns("/**/*.do") .excludePathPatterns("/**/*.html", "/**/*.jsp", "/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg", "/**/*.gif", "/**/*.svg"); } /** * config filter * @return */ @bean public FilterRegistrationBean registerFilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new QrcodeCatFilter()); // registration.addUrlPatterns("*.do"); // registration.addInitParameter("exclusions", "*.css"); // registration.setName("CatFilter"); return registration; }}Copy the code

reference

Github.com/spring-proj…

Jdk8 knowledge

How do I exclude static resource request paths?

Custom extension filter source

package com.xxx.qrcode.ugate.payment.filter; import com.dianping.cat.servlet.CatFilter; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.util.AntPathMatcher; /** * override CatFilter, .js/.css/.html * * @author GZH * @createTime 2021/2/23 2:54pm */ Public class QrcodeCatFilter extends CatFilter Private static List<String> excludeUrlPatterns = array.asList ("/**/*.html", "/**/*.jsp", "/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg", "/**/*.gif", "/**/*.svg"); private static AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// Obtain the relative path of the current request (i.e. the path after removing the domain name/project name) HttpServletRequest HttpServletRequest = (HttpServletRequest)request; String ServletPath = httpServletRequest.getServletPath(); / / check whether the path matching Boolean b = excludeUrlPatterns. Stream () anyMatch (e - > antPathMatcher. Match (e, ServletPath)); If (b) {// If the resource is static, do not go CatFilter chain. DoFilter (request, response); }else {CatFilter super.dofilter (request, response, chain); }}}Copy the code

Exclude static resources, using JDK8 knowledge points.

Get a stream from a collection. This is only available in JDK8.

2. After obtaining the flow, what calculation should be performed on the flow data? Match data. How do you match? Use the anyMatch method to match.

3. The input argument to the anyMatch method is the source code for the Predicate type

public interface Stream<T> extends BaseStream<T, Stream<T>> {
/**
     * Returns whether any elements of this stream match the provided
     * predicate.  May not evaluate the predicate on all elements if not
     * necessary for determining the result.  If the stream is empty then
     * {@code false} is returned and the predicate is not evaluated.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
     * terminal operation</a>.
     *
     * @apiNote
     * This method evaluates the <em>existential quantification</em> of the
     * predicate over the elements of the stream (for some x P(x)).
     *
     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
     *                  <a href="package-summary.html#Statelessness">stateless</a>
     *                  predicate to apply to elements of this stream
     * @return {@code true} if any elements of the stream match the provided
     * predicate, otherwise {@code false}
     */
    boolean anyMatch(Predicate<? super T> predicate);
Copy the code

Predicate types are functional interfaces

/** * Represents a predicate (boolean-valued function) of one argument. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #test(Object)}. * * @param <T> The type of the input to the predicate * * @since 1.8 */ @functionalInterface // Public interface Predicate<T> {public interface Predicate<T> {Copy the code

4. What is E? E is the current element in the stream when iterating through it.

5.AntPathMatcher Pattern Matching path, the spring framework’s own matching path function. There are two key points:

1) *. Do * : matches 0 or multiple characters. 2) /** /** : matches 0 or multiple directoriesCopy the code

reference

Jdk8 of actual combat


conclusion

In addition to using Jdk8 knowledge, to exclude static resource request path, of course, can also use traditional code to exclude. The implementation is to traverse the collection data, and then one data to match the current request path.

Reference: blog.csdn.net/qq_23934475…