Model View Controller (MVC) with JSP and JSTL

In this article we will create a small web application that uses the Model View Controller (MVC) pattern with Java Server Pages (JSP) and JSP Standard Template Library (JSTL). A container like Tomcat is needed to run this combination.

Thanks go out to the author of the JSP – MVC Tutorial, who thought of the sample application that we will use here, the coffee advisor. The user is first presented with a choice in coffee taste she prefers. Pressing a button moves on to a page with advise about the type of coffee to drink based on that taste.

An MVC application has three parts:

  • Model. The model is the domain-specific representation of the data upon which the application operates. In our case this is implemented in the CoffeeExpert class.
  • View. The view renders the model into a form suitable for interaction, typically a user interface element. In our case this is implemented in a JSP file called coffee.jsp.
  • Controller. The controller receives input and initiates a response by making calls on model objects. In our case this is implemented in the CoffeeSelect class.

In addition to these three file we need a web.xml file that tells the container how to map a URL (e.g. /CoffeeSelect.do) into a class to run (e.g. com.example.web.CoffeeSelect). We also need a start page for the user input, which we will call coffee.html. In total this means we should create a  .war file with the following structure:

coffee.html

<html>
    <body>
        <h2>Coffee Advisor Input</h2>
        <form method="POST" action="CoffeeSelect.do">
            <select name="taste" 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/>
            <input type="Submit"/>
        </form>
    </body>
</html>

CoffeeExpert.java

package com.example.model;

import java.util.*;

public class CoffeeExpert {
    public List<String> getTypes(String taste) {
        List<String> result = new ArrayList<String>();
        if (taste.equals("milky")) {
            result.add("Latte");
            result.add("Cappuccino");
        } else if (taste.equals("froffy")) {
            result.add("Latte");
            result.add("Cappuccino");
            result.add("Frappuccino");
        } else if (taste.equals("icey")) {
            result.add("Frappuccino");
        } else if (taste.equals("strong")) {
            result.add("Espresso");
            result.add("Double espresso");
        } else {
            result.add("Vending machine");
        }
        return (result);
    }
}

CoffeeSelect.java

package com.example.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.model.CoffeeExpert;

public class CoffeeSelect extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        List<String> types = new CoffeeExpert().getTypes(request.getParameter("taste"));
        request.setAttribute("types", types);
        RequestDispatcher view = request.getRequestDispatcher("coffee.jsp");
        view.forward(request, response);
    }
}

coffee.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
    <body>
        <h2>Coffee Advisor Output</h2>
        <c:forEach var="type" items="${types}">
            <c:out value="${type}"/>
            <br />
        </c:forEach>
    </body>
</html>

web.xml

<?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 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>/CoffeeSelect.do</url-pattern>
    </servlet-mapping>
</web-app>

14 thoughts on “Model View Controller (MVC) with JSP and JSTL

  1. Permalink  ⋅ Reply

    david

    June 28, 2011 at 2:19pm

    Awesome article!

  2. Permalink  ⋅ Reply

    Anmol Vats

    April 27, 2012 at 2:24pm

    Thanks a ton guys.
    Very Useful information for a Beginner.
    Keep Blogging…

  3. Permalink  ⋅ Reply

    C

    September 6, 2012 at 10:42am

    Finally a complete code that works!
    Thank you! More! 😀

    • Permalink  ⋅ Reply

      ghhg

      May 27, 2013 at 11:44am

      Help me huhuhu error

      HTTP Status 404 –

      type Status report

      message

      description The requested resource is not available.
      Apache Tomcat/7.0.32

  4. Permalink  ⋅ Reply

    varsha

    February 20, 2013 at 6:21am

    really helpful code

  5. Permalink  ⋅ Reply

    Rita

    March 2, 2013 at 10:51am

    Excellent … very easy 2 understand…. n works fine…

  6. Permalink  ⋅ Reply

    jaydeep

    March 22, 2013 at 7:28am

    thank’s for help in jsp mvc arcitecture,
    because i have also little bit idea in jsp mvc arcitecture
    but sir you display above example is very easy to understand and very short
    thank’s sir,

  7. Permalink  ⋅ Reply

    renjith

    April 14, 2013 at 8:34pm

    Nice article. But I got an error in coffee.jsp – “According to TLD or attribute directive in tag file, attribute items does not accept any expressions”

    I fixed it by changing

    to

    in coffee.jsp

  8. Permalink  ⋅ Reply

    mayur

    April 18, 2013 at 9:57am

    thank you for help in jsp mvc arcitecture, plese another extra example …..Thank’s sir.

  9. Permalink  ⋅ Reply

    Vinod

    April 24, 2013 at 7:59am

    I am getting org.apache.jasper.JasperExceptoin in this example

Leave a Reply

Your email will not be published. Name and Email fields are required.