Featured post
java - Get database connection from a connection pool -
i refactoring others code. 1 thing notice of manner on how system getting connection connection pool.
sample this. on every call of service method, system making context lookup on jndi datasource.
public class checkinservlet extends httpservlet { public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { try { //obtain connection initialcontext initialcontext = new initialcontext(); javax.sql.datasource ds = (javax.sql.datasource) initialcontext .lookup("jdbc/mysqldb"); java.sql.connection conn = ds.getconnection(); //business logic //redirect } { conn.close(); } } }
i think there performance hit on doing every time. thinking of way around these on how retrieve connection connection pool.
i thinking using servlet's init()
method think not optimal. idea please? thank you.
do once in servletcontextlistener
instead of everytime in init()
of many servlets. contextinitialized()
method executed once during webapp's startup.
public class config implements servletcontextlistener { private static final string attribute_name = "config"; private datasource datasource; @override public void contextinitialized(servletcontextevent event) { servletcontext servletcontext = event.getservletcontext(); string databasename = servletcontext.getinitparameter("database.name"); try { datasource = (datasource) new initialcontext().lookup(databasename); } catch (namingexception e) { throw new runtimeexception("config failed: datasource not found", e); } servletcontext.setattribute(attribute_name, this); } @override public void contextdestroyed(servletcontextevent event) { // noop. } public datasource getdatasource() { return datasource; } public static config getinstance(servletcontext servletcontext) { return (config) servletcontext.getattribute(attribute_name); } }
configure follows in web.xml
:
<context-param> <param-name>database.name</param-name> <param-value>jdbc/mysqldb</param-value> </context-param> <listener> <listener-class>com.example.config</listener-class> </listener>
you can obtain in servlet follows (init()
or doxxx()
method, choose):
datasource datasource = config.getinstance(getservletcontext()).getdatasource();
i'd refactor step further, jdbc code should preferably placed in own classes, not in servlets. lookup dao pattern.
- Get link
- X
- Other Apps
Comments
Post a Comment