HttpServletRequest.getHeader("X-Real-IP")报错java.lang.IllegalStateException

尼玛拉斯兵 发布于 08/23 17:25
阅读 156
收藏 0

定时任务(就一个定时任务)调一个service,service中注入了HttpServletRequest  request作为参数,定时任务进入方法时,参数request为Current HttpServletRequest,request.getHeader("X-Real-IP")时就报错了,两个类似的项目,配置基本相同,另一个却没事。希望各路大神能给指点一下迷津。

异常信息:

java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
        at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
        at org.springframework.web.context.support.WebApplicationContextUtils.currentRequestAttributes(WebApplicationContextUtils.java:271)
        at org.springframework.web.context.support.WebApplicationContextUtils.access$0(WebApplicationContextUtils.java:270)
        at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:286)
        at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:1)
        at org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:178)

        .................

方法就是普通的方法:

public static String getRemoteHost(HttpServletRequest request){
		if(null != request){
			try {
				String ip = request.getHeader("X-Real-IP");
			    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			        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();
			    }
			    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				return "127.0.0.1";
			}
		}else{
			return "127.0.0.1";
		}
	}
加载中
0
@ccny
@ccny

原因是,外部没有单独的线程绑定到 这个请求。

In this case, use RequestContextListener or RequestContextFilter to expose the current request 

你想要获取这个参数 ,需要使用上面的  的方式 。

你可以,在收到请求时,就把内容获取出来,那个时候,tcp的连接应该还在,在你运行定时,任务时,这个请求的对应的线程已经 ,停了。

0
湖水没了
湖水没了

定时任务哪来的客户请求IP 就根本不应该yourequest对象

返回顶部
顶部