I’m working on a Java based web app which will consist of a couple of JSPs and some servlets. The JSPs and servlets all need to access a proprietary remote resource which is accessible by submitting a text based request over TCP (the response is also plain text).
To facilitate this, I have created a DAO style object with various getXbyId() style methods. Internally, the DAO maintains a SocketPool, that is, a collection of Sockets with synchronized get() and put() methods. Calling get() will cause the pool to grow if it is depleted (I should probably cap the size of the pool but I’m not there yet).
I have the above code working for a single servlet. Specifically, the servlet init() method instantiates the DAO object and stores it as a local object. My plan was to expand on this by putting a single instance of the DAO object into application scope (possibly enforced by making it a singleton). Every JSP and servlet would need to check for the existance of this object in the application scope and initialise it where required. JSPs would be able to use <jsp:useBean> while servlets would be need to do this programmatically (that is, fetch it from application context and instantiate it if the fetch returns null). The problem with the above scenario is that the DAO cannot meaningfully be initialised with a no-arg constructor. It needs arguments to specify the IP address, port etc. for the remote resource. These values are stored in a properties file which I load from the ServletContext (via getResourceAsStream).
The question then is, how should I best go about making a single instance of this DAO object available to all of the servlets and JSPs in my application without lots of repetitive and error prone boiler-plate initialisation code?
Thanks,
Phil
You are re-inventing all sorts of things here:
Parameters, specially data such as port number, ip address, etc. should be defined in using
web.xml, unless you have very compelling reason not to do so. (?)Given that you are (let me guess) trying to hook a noSQL backend to your web-app, ideally you should use
JCA(Java Connector Architecture) mechanisms to isolate the driver. Throwing in blocking network calls and a socket pool (!) from the servlet directly can work, but all bets are off in terms of the guarantees that the Java EE-Web container provides you and I personally would never permit such an hack/app to end up in production servers. Ever.Even if you insist on doing this, having a
ServletContextListenermap the life-cycle of your web-app with the life-cycle of the connector is the way to do this.