spring custom filter / interceptor

Keywords: Apache Java SpringBoot Spring


1, Filter

What is a filter?
You can think of it as a sieve, which filters out some parameters in request and response
1. Import related jar packages
Import the common jar package in the pom file

<!-- commons Shared package, used by filter interceptor -->

Update project after import
2. Define the interface of any output parameter
For example:

public class TestController {
	 * Test filter
	public String testFilter(HttpServletRequest request,
			@RequestParam(value="key"/*Parameter name on link*/,defaultValue="123"/*Default when not assigned*/,required=false)String value1,
			@RequestParam(value="key2"/*Parameter name on link*/,defaultValue="123"/*Default when not assigned*/,required=false)String value3){
		String value2=request.getParameter("key");
		String value4=request.getParameter("key2");
		return "Trump 1 after filter filtration="+value1+",Trump 2="+value2+",Filtered accordion 1="+value3+",Accordion 2="+value4;


This is the access display effect for which no filter has been added:

3. Set up filter storage package
Filters are public
Create the filter package under the basic package, and create the filter parameterFilter (use @ WebFilter annotation, inherit

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
 * Custom filter, filter sensitive strings
import org.slf4j.LoggerFactory;
public class ParameterFilter implements Filter {
	//Add a Logger to the filter
	private final static Logger LG=LoggerFactory.getLogger(ParameterFilter.class);
	/*Custom filtered string array*/
	private String[] names={"Trump","accordion","fuck"};
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		* Modify the parameters in the request request
		* HttpServletRequest The request information in is in the locked state. We can't operate it directly
		* We use HttpServletRequestWrapper to process the request information
		* Continue to optimize, customize wrapper class, inherit HttpServletRequestWrapper, rewrite implementation method
		//Package as httpRequest
		HttpServletRequest httpRequest=(HttpServletRequest) request;
		//Map is locked, modification is not allowed, comment out here
		//Map<String,String[]> maps=httpRequest.getParameterMap();
		//maps.put("key", new String[]{"*****"});
		HttpServletRequestWrapper wrapper=new HttpServletRequestWrapper(httpRequest){
            //Overriding getParameter method, value2 changed
			public String getParameter(String name) {
				String value=httpRequest.getParameter(name);
				//Traverse and replace sensitive words in the array
				for (String string : names) {
						return "**";
				return super.getParameter(name);
			//Overriding getParameterValuesr method, value1 changed
			public String[] getParameterValues(String name) {
				String[] values=httpRequest.getParameterValues(name);
					//Traverse and replace sensitive words in the array
					for (String string : names) {
						values[0]= values[0].replace(string, "*");
				return values;
				return super.getParameterValues(name);
		//Chain is a chain
		chain.doFilter(wrapper, response);


	public void destroy() {
		LG.debug("this is parameter fiter destroy.");

	public void init(FilterConfig filterConfig) throws ServletException {
		LG.debug("this is parameter fiter init.");


4. Register the filter to run when it starts
Create a config package under the basic package, create a new mvc configuration class WebMvcConfig in the package, and register the filter

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 * web mvc Related configuration
 * @author 86158
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.springboot.springb.filter.ParameterFilter;

public class WebMvcConfig implements WebMvcConfigurer{
	 * Register parameter filter
	public FilterRegistrationBean<ParameterFilter> parameterFilter(){
		FilterRegistrationBean<ParameterFilter> file=new FilterRegistrationBean<>();
		file.setFilter(new ParameterFilter());
		return file;

Filter configuration complete
Visit the effect display again:

2, Interceptor

To understand what an interceptor is, first of all, we need to know what a uri is. Generally, we know what a url is. Then, for a uri, go to the figure above:

Is it easy to understand that a uri is equivalent to the mapping path of an access interface
The interceptor gets the uri for all the controller control layers and the html page path through rui to jump the page. Therefore, the interface mapping path should be the same as the html page storage path
1. Custom interceptor
Create a subpackage interceptor under the basic package, create a custom interceptor MyInterceptor, and implement

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

* The user-defined interceptor realizes the function of automatically assembling according to uri without specifying template in modelMap
* Implementation steps: inherit HandlerInterceptor ‐ register as component ‐ rewrite postHandle method 
* ‐‐‐‐ Register addInterceptors in configuration class
@Component	//Register as a spring component
public class MyInterceptor implements HandlerInterceptor {
	private final static Logger LOGGER=LoggerFactory.getLogger(MyInterceptor.class);
	 * Execute before intercept point
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		LOGGER.debug("Pre uri interceptor");
		return HandlerInterceptor.super.preHandle(request, response, handler);
	 *Intercept point execution 
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		LOGGER.debug("Post uri interceptor");
		if(modelAndView==null || modelAndView.getViewName().startsWith("redirect")){
		String uri=request.getServletPath();
		String template=(String) modelAndView.getModelMap().get("template");
		if(StringUtils.isBlank(template)/*template Is empty*/){
			//Save the uri into the template and pass it to index.html
			modelAndView.getModelMap().addAttribute("template", uri);
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

	 * Execute after intercept point
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		LOGGER.debug("After uri interceptor");
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

It's inside modelAndView.getModelMap (). What's the meaning of addAttribute ("template", uri)? Remember that before Hand in hand to teach you how to integrate the ssm framework (4) page development
Is the page splicing function mentioned in

In the interceptor, rui is saved into the template

2. Register interceptor
Like filters, interceptors need to be registered before they can be used. They need to inherit the webmvc config urer class and add the interceptors method again

import com.springboot.springb.interceptor.MyInterceptor;
public class WebMvcConfig implements WebMvcConfigurer{
	//Introduce custom interceptor
	private MyInterceptor myInterceptor;
	 * Register interceptor
	public void addInterceptors(InterceptorRegistry registry) {
		// TODO Auto-generated method stub

Conduct the test
First define a control layer

	 * Page Jump
	 * Jump to html page
	public String hello(ModelMap m){
		User u=userImpl.getUserBywNum("16110201");
		m.addAttribute("user", u);//Pass through parameters for getting center page
		//m. AddAttribute ("template", "test / center"); / / index page gets the stitched page path
		return "index";

center.html content

<section >
   This is springb center<br>
   <p th:text="${user.uWnum}">uWnum</p>

I don't assign a value to the template store here
index page cannot get the value of template on this interface

If the interceptor runs successfully, you will get center.html Contents of
Access effect:


Posted by treppers on Sat, 13 Jun 2020 01:35:15 -0700