Implementing SpringBoot interceptor [simplified]


Sometimes the following vulnerability pages will appear in the project, we can use the interceptor to do a simple interception to avoid this from happening

Visit White Pages Questions

1. Create an interceptor to implement the HandlerInterceptor interface

I only intercept the status of 4xx and 5xx here, you can modify the contents of postHandle at will

package com.yami.shop.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yami.shop.common.exception.YamiShopBindException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CustomHandlerInterceptor implements HandlerInterceptor {
    
    

    /**
     * 访问控制器方法前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    
    
        return true;
    }

    /**
     * 拦截4xx和5xx的状态 返回Json格式的 错误代码和信息 到页面
     * 访问控制器方法后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    
    
        System.out.println(new Date() + "--postHandle:" + request.getRequestURL());
        if (!"".equals(response.getStatus()+"") && modelAndView != null) {
    
    // 防止出现空指针

            // 拦截4xx和5xx的状态
            if(response.getStatus()>=400 && response.getStatus()<600) {
    
    
                String jsonInfo = "{code:"+response.getStatus()+",msg:'访问页面错误'}";
                // 返回Json格式的 错误代码和信息 到页面
                // 我这边是自己项目的抛异常方法,你们可以自己发挥。
                throw new YamiShopBindException(JSONObject.parseObject(jsonInfo).toJSONString());
                
                // modelAndView.setViewName("/err"); 这个是跳转到/err的接口,我没有实现所以注释掉
            }
        }
    }

    /**
     * postHandle方法执行完成后执行,一般用于释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    
    
    }


}

HandlerInterceptorThe interface defines the following three methods:insert image description here

Two, configure the interceptor


/**
 * 拦截器装配
 */
@Configuration
public class OpenApiFilterConfig implements WebMvcConfigurer {
    
     //找到你项目中实现WebMvcConfigurer 这个接口的配置类 配置拦截器

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new CustomHandlerInterceptor())
                .addPathPatterns("/**");
    }
}

addPathPatterns: This method is used to specify the interception path. For example, the interception path is "/**", which means to intercept all requests, including requests for static resources.
excludePathPatterns: This method is used to exclude interception paths, that is, specify requests that do not need to be intercepted by the interceptor. (But I tried it and it didn't work so the above is useless) Usage: Later .excludePathPatterns("/", "/login", "/index").

3. Rendering

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43825761/article/details/128485046
Recommended