Request Handling Using FrontController Pattern

A very important part of the FrontController pattern is that when FrontController recieves a request will initiate the appropriate Controller (or Command,you name it!) and then delegate request to the controller.In order to do that,FrontController, must somehow retrieve from the request the name of the controller and initiate the appropriate controller class.

The first step will ne to retrieve the name of the controller from the request.
String url=request.getRequestURL().substring(request.getRequestURL().lastIndexOf("/") + 1, request.getRequestURL().length());
String controller = url.substring(0, url.indexOf("."));
In the above code snippet,url variable is assigned with the valueIndex.javastuff and controller variable is assigned with the value Index. Later on, in the ControllerFactory class -the class that instantiates and returns the Controller.Not shown in this tutorial- we construct the full name of the Controller and return a new instance of the Controller class.The below snippet shows how is this done:
try {
            String name = "com.javaonly.controllers." + className + "Controller";
            Class controllerClass = Class.forName(name);
            return (Controller)controllerClass.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
As you can see above, name variable is assigned with full name of the Cotroller class.Later on we call Class.forName method to get Cotnroller's class and finally we return a new instance.


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email