Reputation: 31
I've created an Enterprise Application project with an EJB project and one web project and it runs fine. Now I would like to get the IP address of the remote client in the EJB project for some logic in my application. I tried to create a context class in the web part as the following:
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:
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. I'v tried also to include the web project in EJB projcet properties and I get the error "Can't add cyclic references". I'm using Netbeans. How can I get the remote IP address in this case?
Upvotes: 1
Views: 1558
Reputation: 146
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
}
}
Upvotes: 2
Reputation: 5919
Having web code (ServletContext
etc) in EJB layer is not a good idea, that makes your business logic tightly coupled to the presentation layer.
A better solution will be to pass the IP address from the presentation logic, rather than, making the EJB later do the work.
Upvotes: 1