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.