2014-04-05 110 views
39

我對Spring MVC的控制器項目的工作中,我提出來自瀏覽器的GET URL調用 -如何在Spring MVC Controller中提取IP地址獲取調用?

下面是由我提出來自瀏覽器的GET調用的URL -

http://127.0.0.1:8080/testweb/processing?workflow=test&conf=20140324&dc=all 

以下是其中的電話打進來,在瀏覽器擊中後的代碼 -

@RequestMapping(value = "processing", method = RequestMethod.GET) 
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow, 
    @RequestParam("conf") final String value, @RequestParam("dc") final String dc) { 

     System.out.println(workflow); 
     System.out.println(value); 
     System.out.println(dc); 

     // some other code 
    } 

問題陳述: -

現在有什麼辦法,我可以從某個頭文件中提取IP地址?這意味着我想知道從哪個IP地址開始,呼叫即將到來,這意味着誰在URL上方呼叫,我需要知道他們的IP地址。這可能嗎?

回答

76

的解決方案是

@RequestMapping(value = "processing", method = RequestMethod.GET) 
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow, 
    @RequestParam("conf") final String value, @RequestParam("dc") final String dc, HttpServletRequest request) { 

     System.out.println(workflow); 
     System.out.println(value); 
     System.out.println(dc); 
     System.out.println(request.getRemoteAddr()); 
     // some other code 
    } 

添加HttpServletRequest request到你的方法定義,然後使用servlet API

Spring文檔here

15.3.2.3支持的處理方法參數和返回說類型

Handler methods that are annotated with @RequestMapping can have very flexible signatures. 
Most of them can be used in arbitrary order (see below for more details). 

Request or response objects (Servlet API). Choose any specific request or response type, 
for example ServletRequest or HttpServletRequest 
+0

感謝Koitoer的幫助。一個簡單的問題,假設如果調用來自Load Balancer而不是特定的機器,那麼這也會起作用嗎?我猜不是.. – john

+0

沒有它不會,但負載平衡器中有一些配置可以發送IP,因爲它們不存在,可能這是您的情況 – Koitoer

+0

檢查可能負載平衡器可以將這些值發送到標題中,因此請考慮使用HttpServletRequest的getHeader方法。 – Koitoer

61

我在這裏遲到了,但這可能會幫助某人尋找答案。通常servletRequest.getRemoteAddr()的作品。

在很多情況下,您的應用程序用戶可能正通過代理服務器訪問您的Web服務器,或者您的應用程序可能位於負載平衡器後面。

所以你應該在這種情況下訪問X-Forwarded-For http頭來獲取用戶的IP地址。

例如String ipAddress = request.getHeader("X-FORWARDED-FOR");

希望這會有所幫助。

+1

良好的通話。 Upvoted。 – Unheilig

+5

請注意,「X-Forwarded-For」通常是以逗號分隔的ips列表,鏈中的每個代理都會將其看到的遠程地址添加到列表中。所以一個好的實現通常會有一個可信的代理列表,並在從右到左閱讀這個頭時「跳過」那些ips。 – Raman

+0

如何獲取ip地址爲111.111.111.111/X –

1

您可以從RequestContextHolder如下靜態獲取IP地址:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) 
     .getRequest(); 

String ip = request.getRemoteAddr();