MVC Tutorial

This is a simple Model View Controller (MVC) tutorial, although this is a very small application it uses the MVC model approach which proves that even small applications can use MVC. The following is what we will be doing in this tutorial,

You will need the following requirements already setup, you can use either Unix/Linux or Windows the choice is yours

The web application is a Coffee advisor, the user will input the type of Coffee and get back some advise, below is the users input screen

The User will receive the below advise page

Even though this is a small application we'll build it using a simple MVC architecture

  1. The client makes a request for the form.html page
  2. The Container retrieves the form.html page
  3. The Container returns the page to the browser, where the user answers the questions on the form
  4. The browser sends the request data to the Container
  5. The Container finds the correct servlet based on the URL, and passes the request to the servlet
  6. The servlet calls the CoffeeExpert for help
  7. The expert class returns an answer, which the servlet adds to the request object
  8. The servlet forwards the request to the JSP
  9. The JSP gets the answer from the request object
  10. The JSP generates a page for the Container
  11. The Container returns the page to the user

Below is an example for creating your development environment but this is entirely up to you

Below is the deployment environment, here I am using Tomcat deploying a web application involves both Container-specific rules and requirements of the servlet and JSP specification, everything below the coffeeV1 directory is the same regardless of your Container

The HTML form page

This is a simple HTML form page, basically containing a heading and a drop down list, I have already touched on HTML

HTML Form Page

<html>
<title>Coffee Advisor></title>
<body>
  <h1 align="center">Coffee Advisor </h1>
  <form method="POST" action="SelectCoffee.do">
    Select coffee
    Type:
    <select name="type" size=1">
      <option value="milky">Milky</option>
      <option value="froffy">Froffy</option>
      <option value="icey">Icey</option>
      <option value="strong">Spaced Out</option>
    </select>
    <br><br>
    <center>
      <input type="Submit">
    </center>
   </form>
</body>
<html>

Note: the SelectCoffee.do is a logical name as we will not have access to the class file

The Deployment Descriptor

Now we nee to create the deployment descriptor which is called web.xml, see above diagram on where to place this file

Deployment Descriptor

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         Version="2.4">

  <servlet>
    <servlet-name>Coffee</servlet-name>
    <servlet-class>com.example.web.CoffeeSelect</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Coffee</servlet-name>
    <url-pattern>/SelectCoffee.do</url-pattern>
  </servlet-mapping>

</web-app>

Note: I have more information on URL servlet mapping in my Tomcat tutorial

The Controller Servlet and Model Class

What we will be doing here is to create the Model class that will be used by the controller servlet, we have separated out the model class because the model class could be updated to point to a database or another coffee expert source, thus the servlet will not have to be changed, the idea in any OO programming is to think about development at a later date, you don't what a whole load of changes to your application because you want to change one aspect of it, providing your interfaces to classes don't change then development is much easier.

Model Class

package com.example.model;

import java.util.*;

public class CoffeeExpert {
   public List getTypes(String type) {

     List types = new ArrayList();

     if (type.equals("milky")) {
       types.add("latte");
       types.add("cappuccino");
     }
     else if (type.equals("froffy")) {
       types.add("latte");
       types.add("cappuccino");
       types.add("frappuccino");
     }
     else if (type.equals("icey")) {
       types.add("frappuccino");
     }
     else if (type.equals("strong")) {
       types.add("espresso");
       types.add("double espresso");
     }
     else {
       types.add("Vending Machine");
     }
     return(types);
   }
}

# To compile the above class file
javac -d classes src/com/example/model/CoffeeExpert.java

Note: At a later date this Model could become complex by using a database, which in the real world tends to happen

Servlet Controller

package com.example.web;

import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class CoffeeSelect extends HttpServlet {

  public void doPost( HttpServletRequest request,
                      HttpServletResponse response)
                      throws IOException, ServletException {

    String c = request.getParameter("type");

    // Now use our Coffee Model above
    CoffeeExpert ce = new CoffeeExpert();

    List result = ce.getTypes(c);

    // Use the below code to debug the program if you get problems
    //response.setContentType("text/html"):
    //PrintWriter out = response.getWriter();
    //out.println("Coffee Selection Advise<br>");

    //Iterator it = result.iterator();
    //while(it.hasNext()) {
    //  out.print("<br>try: " + it.next());
    //}

    // The results 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("styles", result);
    RequestDispatcher view = request.getRequestDispatcher("result.jsp");
    view.forward(request, response);
  }
}

## To compile the servlet

## UNIX
javac -classpath <tomcat directory>/lib/servlet-api.jar:classes:. -d classes src/com/example/web/CoffeeSelect.java

# Windows (notice the semi-colons instead of colons)
javac -classpath c:/tomcat6/lib/servlet-api.jar;classes;. -d classes src/com/example/web/CoffeeSelect.java

The JSP View

The last thing to do is to create the JSP view that will display the results of the coffee advisor

JSP View

# Create the result.jsp file below

<%@ page import="java.util.*" %>

<html>
<body>
<h1 align="center">Coffee Recommandation JSP View</h1>
<p>

<%
  List styles = (List) request.getAttribute("styles");
  Iterator it = styles.iterator();
  while(it.hasNext()) {
    out.print("<br>try: " + it.next());
  }
%>

</body>
</html>