[英]How to get the remote IP address of a client in EJB project from servlet?
I've created an Enterprise Application project with an EJB project and one web project and it runs fine. 我已经创建了一个带有EJB项目和一个Web项目的企业应用程序项目,它运行良好。 Now I would like to get the IP address of the remote client in the EJB project for some logic in my application.
现在我想在EJB项目中获取远程客户端的IP地址,以获取应用程序中的某些逻辑。 I tried to create a context class in the web part as the following:
我尝试在Web部件中创建一个上下文类,如下所示:
Context.java Context.java
public class Context {
private static ThreadLocal<Context> instance = new ThreadLocal<Context>();
private HttpServletRequest request;
private Context(HttpServletRequest request) {
this.request = request;
}
public static Context getCurrentInstance() {
return instance.get();
}
public static Context newInstance(HttpServletRequest request) {
Context context = new Context(request);
instance.set(context);
return context;
}
public HttpServletRequest getRequest() {
return request;
}
}
And from class in EJB I tried to call the context class like: 从EJB中的类我尝试调用上下文类,如:
public String setIPAddress() {
HttpServletRequest request = Context.getCurrentInstance().getRequest();
String remoteIPAddress = request.getRemoteAddr();
return remoteIPAddress;
}
My problem is I can't call context.java from EJB class and if I include the classe context in the EJB part I get the NullPointerException. 我的问题是我无法从EJB类调用context.java,如果我在EJB部分中包含classe上下文,我会得到NullPointerException。 I'v tried also to include the web project in EJB projcet properties and I get the error "Can't add cyclic references".
我也尝试在EJB projcet属性中包含Web项目,我收到错误“无法添加循环引用”。 I'm using Netbeans.
我正在使用Netbeans。 How can I get the remote IP address in this case?
在这种情况下如何获取远程IP地址?
It is not advisable to do so, but if you need it can use this: 不建议这样做,但如果需要,可以使用:
import javax.ejb.Stateless;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
@Stateless
public class MyServiceBean {
public void initialize() {
final HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
System.out.println("IP:" + request.getRemoteAddr());
// load data
}
}
Having web code ( ServletContext
etc) in EJB layer is not a good idea, that makes your business logic tightly coupled to the presentation layer. 在EJB层中使用Web代码(
ServletContext
等)并不是一个好主意,这会使您的业务逻辑与表示层紧密耦合。
A better solution will be to pass the IP address from the presentation logic, rather than, making the EJB later do the work. 一个更好的解决方案是从表示逻辑传递IP地址,而不是让EJB稍后完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.