简体   繁体   中英

Capture ip address from Spring controller to JSP

My spring app has a controller like this: https://my.app.com/project1/token . When a user clicks this link, I redirect them to a jsp in my WEB-INF folder to collect some client-side data from a jsp (info like langauge, local, time, etc). I want to capture the IP address as well, but I'm not able to get any data from my controller. This is the code I have so far:

servletRequest.setAttribute("ip", servletRequest.getHeader("X-FORWARDED-FOR"));
servletRequest.getRequestDispatcher(DEVICE_INFO).forward(servletRequest, servletResponse);

And in my JSP I have:

console.log("IP address is - ${ip}");

But it is coming up empty. Is there a better solution for this? If I just use servletRequest.setAttribute("ip", servletRequest.getRemoteHost()); I get the ip of the jsp host (which is docker at the moment, I want to get the ip address of the user who clicked the link).

The X-FORWARDED-FOR is only set if there is a proxy in the middle, which is setting that header. If you have no proxy, or the proxy is not setting that header, you will not get anything there.

Did you try something like this?

  String remoteAddr = servletRequest.getHeader("X-FORWARDED-FOR");
  if (remoteAddr == null || remoteAddr.equals("")) {
      remoteAddr = servletRequest.getRemoteAddr();
  }

It works on normal setups, not sure what your docker setup is doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM