JBoss AS 7, Java EE 6 how to get clients IP?

血红的双手。 提交于 2020-01-06 14:04:14

问题


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....


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9778800/jboss-as-7-java-ee-6-how-to-get-clients-ip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!