[英]How to get Client IP address in Spring bean
I have define a Spring bean. 我已经定义了一个Spring bean。
<beans>
<bean id="remoteService" class="edu.wustl.catissuecore.CaTissueApplictionServicImpl" />
</beans>
Is there any way to get the IP address of client in this class? 有没有办法在这个类中获取客户端的IP地址? Similarly as available in the servlet
request.getRemoteAddr()
; 与servlet
request.getRemoteAddr()
可用的类似;
The simplest (and ugliest) approach is to use RequestContextHolder
: 最简单(也是最丑陋)的方法是使用
RequestContextHolder
:
String remoteAddress = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
.getRequest().getRemoteAddr();
Without knowing more about your bean and how it's wired up, that's the best I can suggest. 如果你不了解更多关于你的bean以及它是如何接线的,那就是我能建议的最好的。 If your bean is a controller (either subclassing
AbstractController
or being annotated with @Controller
) then it should be able to get direct access to the request object. 如果你的bean是一个控制器(子类化
AbstractController
或用@Controller
注释)那么它应该能够直接访问请求对象。
The best way to get client ip is to loop through the headers 获取客户端IP的最佳方法是遍历标头
private static final String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
public static String getClientIpAddress(HttpServletRequest request) {
for (String header : IP_HEADER_CANDIDATES) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
Construct this: 构造这个:
@Autowired(required = true)
private HttpServletRequest request;
and use like this: 并使用这样的:
request.getRemoteAddr()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.