Tuesday, 25 June 2013

JSP MVC (model-view-controller) example


This is a simple Model View Controller (MVC) example:

  • Controller: Servlet controller. Let the controller servlet listen on a specific url-pattern of interest in web.xml, and forward the request to the JSP page of interest using RequestDispatcher.
  • Model: A simple java class
  • View: An JSP view


(1) Servlet Controller:
public class ExampleServlet extends HttpServlet {
  public void doPost( HttpServletRequest request,
                      HttpServletResponse response)
                      throws IOException, ServletException {
    // The exampleObject will be passed back (as an attribute) to the JSP view
    // The attribute will be a name/value pair, the value in this case will be a List object
    request.setAttribute("exampleParameter", exampleObject);

    // Forward the request to the JSP page of interest using RequestDispatcher.
    request.getRequestDispatcher("/WEB-INF/example.jsp").forward(request, response);
  }
}

(2) Model
public class ModelExample {
   public Object getExampleObject(String key) {
     ...
     return exampleObject
   }
}

(3) JSP view (example.jsp)
<%@ page import="java...." %>
<html>
<body>
<%
  Object exampleObject = (Object) request.getAttribute("exampleParameter");
  ...
%>
</body>
</html>

References:
http://www.datadisk.co.uk/html_docs/jsp/jsp_mvc_tutorial.htm
http://stackoverflow.com/questions/2575471/how-to-develop-jsp-servlets-web-app-using-mvc-pattern