Quick start springboot web page development filter and interceptor of springboot controller

filter

◼ Filter s can dynamically intercept requests and responses.
◼ Application scenario: filter sensitive words, prevent SQL injection, set character encoding, and perform URL level
Other permissions, access control, compression response information, etc.

Filter programming step 1: create a filter class

◼ Write a Java class to implement the Filter interface (mainly the doFilter() method);
◼ The filter class is annotated with the annotation @ WebFilter, and the filter url is configured.


Three method descriptions of Filter interface:
The Filter starts with the start of the web application, is initialized only once, and is destroyed with the stop of the web application.

  1. Load the instance of the filter when starting the server, and call the init() method to initialize the instance;
  2. Each request only calls the doFilter() method for processing;
  3. When stopping the server, call the destroy() method to destroy the instance

Filter class basic code framework

Filter class basic code framework
@WebFilter("/*") // The current configuration intercepts all requests
public class MyFilter implements Filter {
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
		if(Certain condition){
			//Interception processing
		}
		else{
			chain.doFilter(request, response); // Release
		}
	}
}

Filter programming step 2: load filter

◼ Add the @ ServletComponentScan annotation on the Spring Boot startup class.

Filter programming example: IP blacklist

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebFilter("/*")
public class MyFilter implements Filter {
	//Blacklist simple simulation
	private List<String> IPList=new ArrayList<>();
	@Override
	public void init(FilterConfig filterConfig) throws ServletException { //Filter initialization
		IPList.add("127.0.0.1"); // Local address
		IPList.add("0:0:0:0:0:0:0:1"); // IPv6 native address
	}
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws
	IOException, ServletException {
		//Blacklist filtering
		String ip = servletRequest.getRemoteAddr(); // Get client ip address
		System.out.println(ip); //Check it on the console
		if( IPList.contains(ip) ){
		servletResponse.setContentType("text/html;charset=utf-8"); //Set the character set of the response (avoid Chinese garbled code)
		servletResponse.getWriter().println("You have been blacklisted!");
		}
		else{
		filterChain.doFilter(servletRequest,servletResponse); //Release
		}
	}
}

Interceptor

◼ Interceptor is mainly used to intercept user requests and process them accordingly.
◼ The reflection mechanism based on Java belongs to the application of aspect oriented programming (AOP).
◼ Application scenario: verify user login status, authority verification, record system log, general processing, etc.

Interceptor programming step 1: create interceptor class

Write a Java class to implement the HandlerInterceptor interface (mainly implementing the preHandle() method)

Three method descriptions of HandlerInterceptor interface:
preHandle: called before the service processor processes the request;
postHandle: executed after the business processor processes the request and before generating the view;
After completion: called after the dispatcher servlet has completely processed the request (after rendering the page).

Interceptor class basic code framework

public class MyInterceptor implements HandlerInterceptor {
//Called before processing the request. Permission verification and security control can be carried out;
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception;
// Set conditions for intercepted services
// return true;  Release (release when conditions are met and continue business processing)
// return false;  Intercept (jump to other processing when conditions are not met)
}

Interceptor programming step 2: create interceptor configuration class

◼ Write a Java class to implement the WebMvcConfigurer interface (mainly to implement addInterceptors())
Method)
◼ This class is marked with the annotation @ Configuration (indicating that it is a Configuration class)

Interceptor configuration class basic code framework

@Configuration // Indicates that it is a configuration class. Don't drop it!
public class MyWebConfig implements WebMvcConfigurer {
	@Override
	public void addInterceptors(InterceptorRegistry registry) { //Load interceptor
		registry.addInterceptor( new MyInterceptor () ) //Load custom interceptors
		.addPathPatterns("/**") //The path to intercept requests / * * indicates all requests
		.excludePathPatterns("/","/css/*","/images/*","/js/*"); //Non intercepted requests, such as home page, static resources, etc
	}
}

Keywords: Spring Boot servlet filter

Added by jarvis on Tue, 08 Feb 2022 15:19:27 +0200