springboot使用拦截器Interceptor拦截指定url,进行对应操作

在springboot中,通过使用拦截器,拦截特定url,做相应的处理,简单示例如下:


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * URL拦截,做对应处理
 *
 */
@Component
public class URLInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(URLInterceptor.class);

    /**
     * 请求前置处理(后置处理同理)
     *
     * @param request
     * @param response
     * @param handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        logger.info(path);
        if (path.matches("xxxxx")) {
            logger.info("requestUrl: {}", path);
            // 进行前置处理
            return true;
            // 或者 return false; 禁用某些请求
        } else {
            return true;
        }
    }
}

将拦截器注入

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器注入
 *
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private URLInterceptor urlInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(urlInterceptor);
    }
}

 

 

你可能感兴趣的:(Springboot,interceptor,springboot,java)