Question

I have a simple question, but I'm searching for longer time, but I always found the same answers,which i don't really know how to handle...

i want to get the IP adress of the client, when he registers to my application...

i found something like this:

    @ManagedBean(name="testController")
    @SessionScoped
    public class TestController implements Serializable {

        private static final long serialVersionUID = -3244711761400747261L;
        protected final HttpServletRequest req;

        public TestController(HttpServletRequest req) {
            this.req = req;
            System.out.println(this.req.getRemoteAddr().toString());
        }
    }

but i don't have the HttpServletRequest in the constructor.... or i don't know how to use it, all i get are errors....

Was it helpful?

Solution

It's available by the ExternalContext#getRequest().

public TestController() {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    System.out.println(request.getRemoteAddr());
}

Note that you're making one major conceptual mistake in your initial attempt. You're attempting to assign the current HTTP request as a property of a session scoped managed bean. The HTTP request instance will expire by the end of the current HTTP response and thus not be valid anymore and throw exceptions in all colors when you try to access its methods in the subsequent requests following the initial request when the session scoped bean was been created.

OTHER TIPS

I'd go for a different approach, also used in the Seam Solder project: Make a servlet filter that captures the servlet request and makes it available via an application scoped producer. See corresponding source code of the solder project.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top