I’m using SQLite as my database, and I’m a little bit confused about how I’d configure the path to it. Basically, I have a static String in one of my classes ( which, after initialization turns to something like this ):
private static String DATABASE = "db/my.db";
The folder db is located directly under WebContent, so, to get access to it, I need to use a ServletContext‘s getRealPath method. To use that, I need access to a servlet, and since I’m not sure which servlet will be the first one to be called, I need to perform a check in all of my requests to see if the database has been set, and if it hasn’t then set it. I think there should be a better way of doing this.
For the moment, I created an abstract class which inherits from HttpServlet, adds 2 methods, a getImpl and a postImpl ( both abstract ), and my doGet and doPost are currently implemented like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
App.checkDatabase(this);
try {
getImpl(request,response);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
App.checkDatabase(this);
try {
postImpl(request,response);
} catch(Exception e) {
throw new RuntimeException(e);
}
And my checkDatabase method is implemented like this:
public static void checkDatabase(HttpServlet servlet)
{
if(App.DATABASE == null) {
App.DATABASE = "jdbc:sqlite:"+servlet.getServletContext().getRealPath(
servlet.getServletContext().getInitParameter("DATABASE")
);
}
}
The way I’m doing things right now doesn’t feel right. Surely there must be a better way.
You would like to use a
ServletContextListenerto hook on webapp’s startup and initialize applicationwide parameters. Here’s a kickoff example assuming that you indeed have definied the path as a<context-param>with<context-name>ofDATABASE:Which you then map in
web.xmlas follows:You can if necessary store contextwide variables in
ServletContextso that any servlet in turn can access it.…
As Pascal hinted in his answer, you’d like to use under each JNDI for this. In that case, you can store the JNDI name as
<context-param>and obtain/initialize theDataSource(indirectly) in theServletContextListenerthat way.For more hints you may find this basic example useful.