I have a JavaBean which is being used by servlets in a web application, and I want to access this bean in a Message-Driven EJB in order to update a value in the bean (I'll want to add a message text to a Vector of Strings). In the servlets I can access the bean by getting it as an ServletContext attribute, but I'm not clear as to how I can access this bean within the EJB's onMessage() method, since the EJB doesn't have access to the ServletContext.
- Posted by: James Adams
- Posted on: April 05 2004 11:22 EDT
Can someone suggest how I gain access to this bean within the EJB's onMessage() method ?
Thanks in advance for any feedback.
- Accessing a JavaBean with a Message-Driven EJB by Paul Strack on April 05 2004 11:56 EDT
- Accessing a JavaBean with a Message-Driven EJB by James Adams on April 06 2004 16:22 EDT
Here is what I suggest you do. Rather than updating the Bean directly in your MDB, write a Servlet in your web layer that supports remote updates, using a URL like the following:
In your MDB, invoke this servlet using a java.net.URL object. This way, you can pass your message from your EJB layer into your web layer.
Thanks for the suggestion, this sounds like a good idea.
How would I invoke the URL from within the EJB code ? I don't see any methods in the java.net.URL class for actually invoking the URL after it's been created.
Thanks in advance...
Use the "openConnection()" method of the URL to get a java.net.URLConnection object. Use this object's "connect()" method to make the connection. This will send the request to the servlet. Since you don't care about the response, that is all you need to do (though maybe you could send error messages in the response or something).
One question which comes to mind is whether or not this is inefficiently going across the network to call a servlet which is being served by the same VM (both the servlet and EJB will be running in JBoss). Will the application server (JBoss in my case) be smart enough to figure this out and bypass sending the request across the internet ? Is there one way of specifying the URL which would be more efficient, or help the application server out a bit by specifying something like
http://www.myserver.com:8080/servlet/MyServlet$text="new message" ?
Using http://localhost will help or better yet, http://127.0.0.1. These will avoid a DNS lookup, and should be well optimized.
If you want to avoid this, you might try another trick: bind your global objects to the JNDI namespace rather than storing them in your ServletContext. The JNDI namespace is available everywhere in your server, including both your servlet layer and your EJB layer. This is trickier than my earlier suggestion, but would work better.