Reputation:
I have define a 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? Similarly as available in the servlet request.getRemoteAddr()
;
Upvotes: 5
Views: 33497
Reputation: 81
The best way to get client ip is to loop through the headers
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();
}
Upvotes: 8
Reputation: 9
Construct this:
@Autowired(required = true)
private HttpServletRequest request;
and use like this:
request.getRemoteAddr()
Upvotes: -1
Reputation: 403441
The simplest (and ugliest) approach is to use 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. 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.
Upvotes: 20