Home

JSP and Beyond

a pragmatic primer on building web-based solutions with Java technologies


Model View Controller (MVC) and JavaBean Sample

Up until this point, we have examined many ways to help separate code and business logic from your JSPs. JSTL, JavaBeans and custom tags all go a long way toward doing this. As applications grow in size, it also make sense to abstract additional things like page flow and security, in addition to making any separation of design and code even further pronounced. The Model View Controller framework is the result of a natural evolution toward this approach.

This sounds magical! How does it work?

Think of an MVC framework like a person traveling by train throughout Europe.

When people want to travel from one place to another, they need to see the conductor with their ticket and baggage. The ticket informs the conductor where they are headed, and perhaps it is to the city of Paris or London. After checking to make sure that the person is okay to travel to the requested destination, the conductor helps to load their baggage to ensure that it is sent with them. Once the person has arrived, the conductor assists them off the train where they are surrounded by new sights.

How does that relate back to MVC?

The “C” or controller in MVC is the conductor. The controller, which is generally a Servlet, intercepts all requests that an end user makes and captures the data that is sent with the requests. In an MVC framework, the requests are sent with an “action” which is the equivalent of the ticket, and the baggage is the equivalent of the data that is paired with the request. The controller also ensures that people are authorized to access a particular action. The controller will then let any business take place as it connects with the Model or “M” which controls database and external resource access. Once the processing in the model is completed, the controller will route people to a particular View or “V”. The view is generally a JSP that correlates to the action requested of the controller.

In the example below, we take a basic approach to MVC, using a single Servlet to capture and deal with all requests. In a more formal implementation a framework like Jakarta Struts would probably be used to manage the application, especially as the size of the application increases.

Controller Servlet
The controller Servlet is the heart of the MVC version of the reference application. It takes almost all of the Java code out of the JSPs, leaving only some JSTL and EL to assist with the presentation. You do not need to memorize the example below, but you can quickly see that the controller cues off of the “action” that is requested of it such as::

else if (”customerlist”.equals(action))

When a request is sent to the controller, it is formatted like:
http://localhost:8084/JSPandBeyond/MVCSample/ServletExample?action=customerlist

This tells the application that you would like to see the customer list. The controller will then get an array of customer beans ready to be sent back to the JSP, where you can render the results to the end user via JSTL and EL.

What you will also notice in the controller Servlet is that it will delegate all database work to another class, thereby enhancing the readability of the code in your controller.

ServletExample.java

/*
* JSP and Beyond
* Servlet example for simple Model View Controller
*/

package JSPBeyond;

// Below are the default namespaces that are used for Servlets
import java.io.*;
import java.net.*;
import javax.Servlet.*;
import javax.Servlet.http.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ServletExample extends HttpServlet {

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// Get the action argument from the URL
String action = request.getParameter(”action”);

// Set the default page for the Servlet to redirect to
String jspPage = “CustomerList.jsp”;

// Advanced error / request handling
if ((action == null) || (action.length() < 1))
{
action = “default”;
}
if (”default”.equals(action))
{
jspPage = jspPage;
}
else

if (”customerlist”.equals(action))
{
// Create arraylist to house the customer listing
java.util.ArrayList alCustomers;
try
{
alCustomers = JSPBeyond.ServletExampleData.getCustomers();

// Set the “CustomerListing” attribute so it can hold the array for access later within this page
request.setAttribute(”CustomerListing”, alCustomers);
}
catch (Exception ex)
{
// Exception
}
jspPage = “CustomerList.jsp”;
}

else if (”addcustomer”.equals(action))
{
jspPage = “CustomerAdd.jsp”;
}

else if (”deletecustomer”.equals(action))
{
if (request.getParameter(”CustomerID”) != null)
{
try
{
// Call our data method to handle the deletion
JSPBeyond.ServletExampleData.deleteCustomer(Integer.parseInt(request.getParameter(”CustomerID”).toString()));
}
catch (Exception ex)
{
// Exception handle
}
}
jspPage = “CustomerDelete.jsp”;
}

else if (”savecustomer”.equals(action))
{
if (request.getParameter(”CustomerName”) != null)
{
try {
// Call our data method to handle the deletion
JSPBeyond.ServletExampleData.addCustomer(request.getParameter(”CustomerName”));
}
catch (Exception ex)
{
// Exception handle
}
}
jspPage = “CustomerAdd.jsp?status=complete”;
}

else if (”addnote”.equals(action))
{
if (request.getParameter(”CustomerID”) != null)
{
request.setAttribute(”CustomerID”, request.getParameter(”CustomerID”).toString());
}
jspPage = “NoteAdd.jsp”;
}

else if (”customerdetails”.equals(action))
{
if (request.getParameter(”CustomerID”) != null)
{
try {
Integer iCustomerID = Integer.parseInt(request.getParameter(”CustomerID”));
String sCustomerName = “”;

sCustomerName = JSPBeyond.ServletExampleData.getCustomerName(iCustomerID);

// Create arraylist to house the customer listing
java.util.ArrayList NoteRecords;
NoteRecords = JSPBeyond.ServletExampleData.getNotes(iCustomerID);

// set the customer ID to head into the page
request.setAttribute(”CustomerID”, iCustomerID.toString());
request.setAttribute(”noteListing”, NoteRecords);
request.setAttribute(”customerName”, sCustomerName);
}
catch (Exception ex)
{
// Handle exceptions here
}
}
jspPage = “CustomerDetails.jsp”;
}

else if (”editcustomer”.equals(action))
{
if (request.getParameter(”CustomerID”) != null)
{
try {
Integer iCustomerID = Integer.parseInt(request.getParameter(”CustomerID”).toString());

String sCustomerName = JSPBeyond.ServletExampleData.getCustomerName(iCustomerID);

// set the customer name
request.setAttribute(”CustomerName”, sCustomerName);
request.setAttribute(”CustomerID”, iCustomerID.toString());
}
catch (Exception ex)
{
// Handle the exception
}
}
jspPage = “CustomerEdit.jsp”;
}

else if (”saveeditcustomer”.equals(action))
{
if (request.getParameter(”CustomerID”) != null)
{
try {
Integer iCustomerID = Integer.parseInt(request.getParameter(”CustomerID”));
String sCustomerName = request.getParameter(”CustomerName”);

JSPBeyond.ServletExampleData.updateCustomer(iCustomerID, sCustomerName);
}
catch (Exception ex)
{
// Exception handle here
}
}
jspPage = “CustomerEdit.jsp?status=complete”;
}

else if (”savenote”.equals(action))
{
if (request.getParameter(”CustomerID”) != null)
{
try
{
String sNote = request.getParameter(”Note”).toString();
Integer iCustomerID = Integer.parseInt(request.getParameter(”CustomerID”).toString());

JSPBeyond.ServletExampleData.addNote(sNote, iCustomerID);
}
catch (Exception ex)
{
// Exception handle here
}
}
jspPage = “NoteAdd.jsp?status=complete”;
}

dispatch(jspPage, request, response);
}

protected void dispatch(String jsp, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
if (jsp != null)
{
RequestDispatcher rd = request.getRequestDispatcher(jsp);
rd.forward(request, response);
}
}

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

private void println(String string) {
throw new UnsupportedOperationException(”Not yet implemented”);
}
}

ServletExampleData.java

package JSPBeyond;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
*
* @author jbrunswi
*/
public class ServletExampleData {

/** Creates a new instance of ServletExampleData */
public ServletExampleData() {
}

private static Connection getConnection ()
{
Connection conn = null;

try
{
// Reference the JDBC driver
Class.forName(”com.mysql.jdbc.Driver”).newInstance();
conn = DriverManager.getConnection(”jdbc:mysql:///PortletCRM”,”root”, “ax355b”);
}
catch (Exception ex)
{
return null;
}
return conn;
}

public static void deleteCustomer (Integer iCustomerID)
{
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();

stmt.executeUpdate(”DELETE FROM tblCustomer WHERE CustomerID = ‘” + iCustomerID.toString() + “‘”);

stmt.close();
conn.close();
}
catch (Exception ex)
{

}
}

public static void updateCustomer (Integer iCustomerID, String sCustomerName)
{
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();

stmt.executeUpdate(”UPDATE tblCustomer SET CustomerName = ‘” + sCustomerName + “‘ WHERE CustomerID = ‘” +
iCustomerID.toString() + “‘”);

stmt.close();
conn.close();
}
catch (Exception ex)
{
// Exception handling
}
}

public static void addNote (String sNote, Integer iCustomerID)
{
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();

stmt.executeUpdate(”INSERT INTO tblNote (CustomerID, Note) VALUES (” + iCustomerID.toString() + “, ‘” + sNote + “‘)”);

stmt.close();
conn.close();
}
catch (Exception ex)
{
// Handle exception
}
}

public static void addCustomer (String sCustomerName)
{
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();

stmt.executeUpdate(”INSERT INTO tblCustomer (CustomerName) VALUES (’” + sCustomerName + “‘)”);

stmt.close();
conn.close();
}
catch (Exception ex)
{
// Exception handling
}
}

public static ArrayList getCustomers() throws Exception
{
Connection conn = getConnection();
Statement stmt = null;
ResultSet rs = null;

ArrayList CustomerRecords = new ArrayList();

// Create a string that has the SQL statement gets records from ‘emp’
String sqlString = “SELECT * FROM tblCustomer ORDER BY CustomerName”;

stmt = conn.createStatement();
rs = stmt.executeQuery(sqlString);

try {
// Add the ResultSet value to an ArrayList. ‘ename’,'job’
while (rs.next())
{
CustomerRecord myCustomerRecord = new CustomerRecord();

myCustomerRecord.setCustomerID(Integer.parseInt(rs.getString(”CustomerID”)));
myCustomerRecord.setCustomerName(rs.getString(”CustomerName”));

CustomerRecords.add(myCustomerRecord);
}
}
catch (Exception ex)
{
throw ex;
}

rs.close();
stmt.close();
conn.close();

return CustomerRecords;
}

public static ArrayList getNotes(Integer iCustomerID)
{
Connection conn = getConnection();

ArrayList NoteRecords = new ArrayList();

try {
Statement stmt = conn.createStatement();
stmt = conn.createStatement();

String sqlString = “SELECT * FROM tblnote WHERE CustomerID = ‘” +
iCustomerID.toString() + “‘”;

ResultSet result = stmt.executeQuery(sqlString);

try {
while (result.next())
{
NoteRecord myNoteRecord = new NoteRecord();
myNoteRecord.setNoteID(Integer.parseInt(result.getString(”NoteID”)));
myNoteRecord.setNote(result.getString(”Note”));
NoteRecords.add(myNoteRecord);
}
}
catch (Exception ex)
{
throw ex;
}

result.close();
stmt.close();
conn.close();
}
catch (Exception ex)
{
// Handle the exception
}

return NoteRecords;
}

public static String getCustomerName (Integer iCustomerID)
{
String sCustomerName = “”;

try
{
Connection conn = getConnection();
Statement stmt = conn.createStatement();

ResultSet result = stmt.executeQuery(”SELECT * FROM tblCustomer WHERE CustomerID = ‘” +
iCustomerID.toString() + “‘”);

if(result.next())
{
sCustomerName = result.getString(”CustomerName”);
}
}
catch (Exception ex)
{
// Handle exception
}

return sCustomerName;
}
}

Customer Listing
In the following example you can immediately notice how clean the JSP becomes as all data work has been abstracted away from anything in the JSP.

<%@ page contentType=”text/html” %>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core_rt” %>
<html>
<head>
<title>JSP and Beyond - Customer List - MVC Example</title>
</head>
<body>

<h1>Customer List - MVC Example</h1>

<table width=”100%” border=”1″>
<tr>
<td colspan=”4″>Customer</td>
</tr>

<%– Start a loop through the contents sent by the controller Servlet and mix it with HTML –%>
<c:forEach var=”row” items=”${CustomerListing}”>
<tr>
<%– Notice how with each “row” object we can access the column name by specifying it after the “row” object –%>
<td><c:out value=”${row.customerName}”/> <a href=”ServletExample?action=customerdetails&CustomerID=<c:out value=”${row.customerID}”/>”>show details</a> </td>
<td><a href=”ServletExample?action=editcustomer&CustomerID=<c:out value=”${row.customerID}”/>”>edit</a></td>
<td><a href=”ServletExample?action=addnote&CustomerID=<c:out value=”${row.customerID}”/>”>add note</a></td>
<td><a href=”ServletExample?action=deletecustomer&CustomerID=<c:out value=”${row.customerID}”/>”>delete</a></td>
</tr>
</c:forEach>
</table>

<br>
<a href=”ServletExample?action=addcustomer”>Add a New Customer</a>
</body>
</html>
Adding a Customer
To add a customer you will still make use of some JSTL to leverage a single JSP. The code is much cleaner and easy to understand.

<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8″%>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core_rt” %>

<html>
<head>
<title>JSP and Beyond - Add Customer - JSTL Example</title>
</head>
<body>

<c:if test=”${param.status != ‘complete’}”>
<h1>Add Customer - JSTL Example</h1>
<form method=”post” action=”ServletExample?action=savecustomer”>
Customer Name
<input type=”text” name=”CustomerName”>
<br><br>
<input type=”submit” value=”Add Customer”>
</form>
</c:if>
<c:if test=”${param.status == ‘complete’}”>

<h1>Add Customer - Customer Added</h1>
<br>
<a href=”ServletExample?action=customerlist”>Main Menu</a>

</c:if>

</body>
</html>

Updating a Customer
Editing a customer is just as simple as adding the customer. When you begin editing a customer account, the controller Servlet takes care of fetching the data that you want to be placed into the form.

<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8″%>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core_rt” %>

<html>
<head>
<title>JSP and Beyond - Customer Edit - MVC Example</title>
</head>
<body>

<c:if test=”${param.status != ‘complete’}”>
<h1>Edit Customer Name - MVC Example</h1>
<form method=”post” action=”ServletExample?action=saveeditcustomer”>
Add Note
<input type=”text” name=”CustomerName” value=”${CustomerName}”>
<input type=”hidden” name=”CustomerID” value=”${CustomerID}”>
<br><br>
<input type=”submit” value=”Save Edit”>
</form>
</c:if>
<c:if test=”${param.status == ‘complete’}”>
<h1>Customer Edit Complete - MVC Example</h1>
<br>
<a href=”ServletExample?action=customerlist”>Main Menu</a>
</c:if>

</body>
</html>