0

Below you can see a method that return an IP address.

I'd like to use it in a JSF page. How can I achieve this?

public static String getClientIpAddr(HttpServletRequest request) {  
  HttpServletRequest request = (HttpServletRequest)    FacesContext.getCurrentInstance().getExternalContext().getRequest();
  String ipAddress = request.getHeader("X-FORWARDED-FOR");
  if (ipAddress == null) {
      ipAddress = request.getRemoteAddr();
  }
  return ipAddress;
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Marcos
  • 844
  • 3
  • 10
  • 25
  • 2
    There is no best way. Me: I'd just return it through a JSF managed bean property that calls the utility function. – Gimby Dec 16 '13 at 12:18
  • please supply your jsf page – Hatem Alimam Dec 16 '13 at 12:24
  • It's a pretty simple program. Actually, it is a contact form. I'd like to catch IP address to show it and write on database together the others fields. – Marcos Dec 16 '13 at 12:38
  • What the `HttpServletRequest request` parameter is supposed to do in your method? – Aritz Dec 16 '13 at 14:43
  • possible duplicate of [How to create a custom EL function?](http://stackoverflow.com/questions/7079978/how-to-create-a-custom-el-function) – BalusC Dec 16 '13 at 15:47
  • By the way, the `X-Forwarded-For` header contains multiple IP addresses commaseparated ... If you're using OmniFaces, better use `Faces#getRemoteAddr()`. That `HttpServletRequest` argument which you never use locally (and is causing uncompilable code) is also weird. – BalusC Dec 16 '13 at 15:49

3 Answers3

1

Your java function have doublicate variable names. Look at the function parameter (request) and at the local variable name request.

Remove the function parameter, cos you get it from facesContext.

you can access the result by a direct function call from the view like :

<h:outputText value="#{myBean.getClientIpAddr()}" />
Sence
  • 115
  • 8
1

If all you have to do is work with request to show the IP in the view, you don't even need to call a method from a managed bean, you can do it directly in your Facelet:

<p>
    IP of request: #{empty header['X-FORWARDED-FOR'] ? request.remoteAddr : header['X-FORWARDED-FOR']}
</p>
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
-1

What about this: "#{request.getHeader('X-FORWARDED-FOR') != null ? request.getHeader('X-FORWARDED-FOR') : request.remoteAddr}"

skybber
  • 409
  • 4
  • 13