Introduction to MVC with Servlets and JSP

Model-View-Controller (MVC) is a pattern used in software engineering to separate the application logic from the user interface.

As the name implies, the MVC pattern has three layers. The model defines the business layer of the application, the view defines the presentation layer of the application, and the controller manages the flow of the application.

Although the MVC pattern is not specific to web applications, it fits very well in this type of applications. In web applications with Java, the model consists of simple Java classes, the view consists of JSP pages, and the controller consists of servlets.

Let’s use the sample we’ve been working on for the last two posts. If you want to create a new project in NetBeans, you’ll need the two classes from the last two projects that represent the business layer.

The first class is ServletSample.Business.Product.

package ServletSample.Business;

public class Product {
    private int id;
    private String name;
    private float price;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }

    public Product(){
        this.id = -1;
        this.name = "";
        this.price = 0f;
    }

    public Product(int id, String name, float price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

}

The second class is ServletSample.Business.ProductService.

package ServletSample.Business;

import java.util.List;
import java.util.ArrayList;

public class ProductService {

    public List<Product> getProducts(){
        List<Product> products = new ArrayList<Product>();
        products.add(new Product(1,"HP Laptop",799f));
        products.add(new Product(2,"IBM Desktop",599f));
        products.add(new Product(3,"Cannon Printer",159f));
        return products;
    }

    public Product getProduct(int id) {
        Product product = null;
        switch(id)
        {
            case 1:
                product = new Product(1,"HP Laptop",799f);
                break;
            case 2:
                product = new Product(2,"IBM Desktop",599f);
                break;
            case 3:
                product = new Product(3,"Cannon Printer",159f);
                break;
        }
        return product;
    }
}

Now let’s add a servlet to the project. You can refer to the post where I showed how to create a servlet for the corresponding steps.

package ServletSample.Web;

import ServletSample.Business.ProductService;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProductServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        ProductService service = new ProductService();
        String value = request.getParameter("id");
        if (value != null) {
            int id = Integer.parseInt(value);
            request.setAttribute("single_product", service.getProduct(id));
        } else {
            request.setAttribute("product_list", service.getProducts());
        }
        getServletConfig().getServletContext().getRequestDispatcher("/product.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

}

This servlet is the controller of our little application.

First, it tries to read a parameter from the request. Depending on if there’s a parameter or not, it gets a product or all of the products from the model (business layer).

Once it retrieved the necessary data from the model, it saves this data in the request using the setAttribute method.

Finally, the controller forwards the request and response objects to a JSP, the view of the application. To do this, we first call the getRequestDispatcher method to get a RequestDispatcher object with the path of the JSP. Then we call the forward method of this object.

If you compare this servlet with the one we created in our previous post, you’ll notice how much smaller and cleaner the new servlet is.

Now let’s create the JSP. You can refer to the post where I showed how to create a JSP for the corresponding steps.

<%@ page contentType="text/html" pageEncoding="UTF-8"%>

<%@ page import="ServletSample.Business.Product" %>
<%@ page import="ServletSample.Business.ProductService" %>
<%@ page import="java.text.DecimalFormat" %>
<%@ page import="java.util.List" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>MVC Sample</title>
    </head>
    <body>
        <%
        if (request.getAttribute("single_product") != null) {
            Product product = (Product)request.getAttribute("single_product");
        %>

        <h1>Product Details</h1>
        <div>ID: <%= product.getId()%></div>
        <div>Name: <%= product.getName()%></div>
        <div>Price: $ <%= new DecimalFormat("#0.00").format(product.getPrice()) %></div>
        <div><a href="product">Go Back</a></div>

        <% } else { %>

        <h1>Product List</h1>
        <table>
            <tr>
                    <td><b>Name</b></td>
                    <td><b>Options</b></td>
            </tr>

            <% for (Product product : (List<Product>)request.getAttribute("product_list")) {%>

            <tr>
                <td><%= product.getName()%></td>
                <td><a href="product?id=<%= product.getId()%>">Details...</a></td>
            </tr>
            <% }
          }%>

        </table>
    </body>
</html>

This JSP is the view of the application. It receives all the information it needs from the controller. It doesn’t need to call the business layer directly.

You’ll notice that this JSP has less Java code than the JSP from our previous post. But there’s still some Java code in the JSP. I’ll show you the tools JSP has to get rid of that code in another post.

Go ahead and run the project. Type product in the URL. The Product List will appear.

Product List With MVC

Notice how we type the URL of the servlet, our controller, not the URL of the JSP.

Click on one of the links.

Product Details With MVC

The product details are shown. Click on the link to go back to the product list.

Please leave your comments or suggestions.

Get Free Updates
Related Posts
Comments