Wednesday, February 23, 2011

Web MVC framework-Controllers

Controllers in Web MVC framework, interpret user inputs and transform such input in to a view that is to be viewed by the user. Spring has implemented several controllers in a very abstractive way. They are form-specific controllers, command-based controllers and controllers that execute wizard-style logic. Spring's basic for the controllers is the org.springframework.web.servlet.mvc.Controller  interface.

public interface Controller {
    ModelAndView handleRequest(
        HttpServletRequest request,
        HttpServletResponse response) throws Exception;
}

handleRequest method is responsible for handling a request and returning an appropriate modelandview.

AbstractController - Spring controllers inherit the AbstractController to get a basic infrastructure. Then we have to override the method handleRequestInternal(HttpServletRequest, HttpServletResponse). Here is an example.

public class MyController extends AbstractController {

    public ModelAndView handleRequestInternal(
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView("hello");
        mav.addObject("message", "Hello World!");
        return mav;       
    }
}

ParameterizableViewController - This is same as the AbstractController except we can specify the view name that it will return in the web application context.

UrlFilenameViewController - This checks the URL and retrieves the file name of the file request and uses that as the view name.

MultiActionController - This allows the aggregation of multiple request handling methods to one controller.

Command Controllers

Command controllers allow to interact with data objects and dynamically bind the parameters from the HttpServletRequest to the data object specified.

AbstractCommandController - This is a command controller that is capable of binding request parameters to a data object. This controller does not provide form functionality.

AbstractFormController - Provides the form submission support.

SimpleFormController - A form controller that provides even more support when creating a form with a corresponding command object.

No comments:

Post a Comment