Java Servlets - Front Controller Questions (Listeners & Context)

256 views Asked by At

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).

1

There are 1 answers

0
user987339 On BEST ANSWER

Main intent for Front controller is to provide a centralized entry point for handling requests and consequently

to control navigation across a set of related pages (for instance, multiple pages might be used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation

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 inside ServletContextListener class will run before the web application starts.