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

1
  • 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. Commented Jan 2, 2014 at 13:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.