使用拦截器获取用户真实IP地址

@Log4j2
public class MyInterceptor extends HandlerInterceptorAdapter {
    private static final String USER_AGENT = "user-agent";

    /**
     * 重写前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入了preHandle");

        if(log.isInfoEnabled()){
            String uri = request.getRequestURI();
            log.info(uri);
            log.info("UserAgent: {}", request.getHeader(USER_AGENT));
            log.info("用户访问地址: {}, 来路地址: {}", uri, getIpAddr(request));
        }
        return true;
    }

    /**
     * 获取真实IP
     * @param request
     * @return
     */
    public  String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        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.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}

然后再写一个类继承  WebMvcConfigurationSupport 这个类 , 重写  addInterceptors方法 ,添加拦截器配置 ;

@Component
public class WebAppConfigurer extends WebMvcConfigurationSupport {

    /**
     * 添加拦截器配置
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //可以添加多个拦截器
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

 

你可能感兴趣的:(JAVA)