springboot拦截器拦截IP

时间:2024-04-09 09:05:47

springboot拦截器拦截IP

新建MyWebMvcConfigurerAdapter

springboot拦截器拦截IP

代码

博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**

  • @ClassName 拦截器

  • @Author panshengbin

  • @Date 2018/9/10 11:47
    **/
    @Configuration
    public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Bean
    public HandlerInterceptor getMyInterceptor(){
    return new MyInterceptor();
    }

    /**

    • 配置静态资源
      */
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/static/").addResourceLocations(“classpath:/static/”);
      registry.addResourceHandler("/templates/
      ").addResourceLocations(“classpath:/templates/”);
      super.addResourceHandlers(registry);
      }

    public void addInterceptors(InterceptorRegistry registry) {
    //addPathPatterns 用于添加拦截规则
    //excludePathPatterns 用于排除拦截
    registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**")
    .excludePathPatterns("/toerror"); //错误页面
    super.addInterceptors(registry);
    }
    }

excludePathPatterns 在这里需要配置排除拦截的地址, 即拦截器拦截后重定向的地址

新建 MyInterceptor

springboot拦截器拦截IP

代码

package com.lx100.common.config;

import com.lx100.common.utils.SysConfigUtils;
import com.lx100.currency.net.HttpApi;
import com.lx100.currency.pojo.RespMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import retrofit2.Call;
import retrofit2.Response;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**

  • @ClassName 拦截器

  • @Author panshengbin

  • @Date 2018/9/10 11:05
    **/
    @Component
    public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private HttpApi httpApi;

    //在请求处理之前进行调用(Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String url = request.getRequestURI();
    System.out.println(“url = " +url);
    String ip = SysConfigUtils.getIpAddress(request);
    System.out.println(“ip = “+ ip);
    if(ip.equals(“127.0.0.1”)) {
    System.out.println(”=拦截到ip===”);
    String str1 = request.getScheme()+”????/"+request.getServerName()+request.getContextPath()+"/toerror";
    System.out.println("str1 = "+ str1);
    response.sendRedirect(str1);
    return false;
    }
    return true;
    }

    //请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    //在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
    }

获取ip

/**
* 获取对象的IP地址等信息
*
* 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
*
* 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
* 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
*
* 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130,
* 192.168.1.100
*
* 用户真实IP为: 192.168.1.110
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
String ip = request.getHeader(“X-Forwarded-For”);

    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
    } else if (ip.length() > 15) {
        String[] ips = ip.split(",");
        for (int index = 0; index < ips.length; index++) {
            String strIp = (String) ips[index];
            if (!("unknown".equalsIgnoreCase(strIp))) {
                ip = strIp;
                break;
            }
        }
    }
    return ip;
}