springboot拦截器实现

Posted 电影公众号

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot拦截器实现相关的知识,希望对你有一定的参考价值。

package webapp.dao.bcf;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import webapp.dao.db.DbWaterApi;
import webapp.models.water.WhitelistModel;
import webapp.utils.HttpUtil;

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

/**
 * @Author:VIC
 * @Description:
 */
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new IPInterceptor()).addPathPatterns("/**");
    }

    public class IPInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
            //IP白名单校验
            String ip = HttpUtil.getIP(request);
            WhitelistModel ipWhite = DbWaterApi.getIPWhite(ip);
            if (ipWhite.row_id == 0)
                return false;
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        }

        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

        }
    }
}

  

以上是关于springboot拦截器实现的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot拦截器----addInterceptors

SpringBoot2----拦截器和文件上传功能

springboot + @ControllerAdvice + @ExceptionHandler 实现全局异常拦截,不用

SpringBoot拦截器

SpringBoot实现登录拦截器(实战版)

OkHttpInterceptor 从 kotlin 拦截器导航到登录片段