Spring MVC コントローラーの get 呼び出しで IP アドレスを抽出するにはどうすればよいでしょうか? 質問する

Spring MVC コントローラーの get 呼び出しで IP アドレスを抽出するにはどうすればよいでしょうか? 質問する

私はブラウザからGET URL呼び出しを行うSpring MVCコントローラープロジェクトに取り組んでいます -

以下はブラウザから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 アドレスを知る必要があるのです。これは可能ですか?

ベストアンサー1

解決策は

@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サーブレットAPIを使用する

Spring ドキュメントここ言った

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

おすすめ記事