2

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

Tim Zimmermann
  • 6,132
  • 3
  • 30
  • 36
  • 1
    Don't think it is related to the question, but in the first case you are initializing the datasource,connection etc only once , i.e. when the context is initialized . In second case , this action will be repeated for each request provided all the requests are routed through the FrontController. – AllTooSir Jan 02 '14 at 13:07

1 Answers1

1

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.

user987339
  • 10,519
  • 8
  • 40
  • 45