For the current project I'm working on, I've decided to use the front controller pattern. I've always been under the impression that a front controller should (ultimately) be responsible for everything that happens in a web app. Would listeners violate this pattern?
public class MyDatabase implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
...
String driver = context.getInitParameter("driver");
}
}
This, of course, seems a lot simpler than:
public class FrontController extends HttpServlet {
public void service (....) {
MyDatabase db = new MyDatabase(context.getInitParameter("driver"));
}
}
This is a very simplified example; there would be more parameters in practice. So, which snippet would be considered more faithful to the front controller pattern – passing the config from FrontController
down, or supplying the config directly to the classes?
As I am new to Java, I am trying to learn servlets without using a framework (for the time being).
Main intent for Front controller is to provide a centralized entry point for handling requests and consequently
Separating responsibility of initialization of resources from Front controller pattern is good, and you choose a right place for this since
ServletContextListener
is responsible for receiving notification events about ServletContext lifecycle. Code insideServletContextListener
class will run before the web application starts.