Visitor ControllerS2C Home « Visitor Controller
In this lesson we take our final look at the controller part of the MVC paradigm and code the controller components for visitors to the web site.
For any visitor to the site, other than the trader, we will use the CustomerFacilities
Java servlet class to direct flow after the visitor has entered the website, or has pressed a particular link on the website.
After control is dispatched to the relevant module via the front controller if the database needs to be accessed to populate the view, or to action user input, then control is passed to the relevant module for processing as follows:-
For any visitor control is passed to the CustomerProcessInput
Java servlet class which calls the CustomerDBAccess
Java servlet class (discussed below) with the appropriate parameters for retrieval of data.
Compiling The CusomerFacilities
ClassTop
For visitors to the web site, we will use the CustomerFacilities
Java servlet class to direct flow after the visitor has entered the website, or has pressed a particular link on the website.
Cut and paste the following code into your text editor and save it in the c:\_ServletsJSP_Case_Study\bstrader\src\controller directory as CustomerFacilities.java
.
package controller;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CustomerFacilities extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String CONTENT_TYPE = "text/html";
// Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
// Decide which customer facility JSP we have come from
String label = request.getParameter("CustFacility");
if (label != null) {
if ("BootSale Information".equals(label)) {
request.setAttribute("action", "GetBSLocDiary");
gotoServlet("/customerprocessinput", request, response);
} else if ("Product Search".equals(label)) {
request.setAttribute("action", "GetSI");
request.setAttribute("label", "Product Search");
gotoServlet("/customerprocessinput", request, response);
} else if ("Best Sellers".equals(label)) {
request.setAttribute("action", "GetSI");
request.setAttribute("label", "Best Sellers");
gotoServlet("/customerprocessinput", request, response);
} else if ("Register With Us".equals(label)) {
request.setAttribute("action", "ShowRUForm");
request.setAttribute("label", "Register With Us");
gotoServlet("/customerprocessinput", request, response);
} else if ("Feedback Form".equals(label)) {
request.setAttribute("action", "GetSIRU");
request.setAttribute("label", "Feedback Form");
gotoServlet("/customerprocessinput", request, response);
}
}
}
// Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
// Decide which customer facility JSP we have come from
String label = request.getParameter("label");
if (label != null) {
if ("Registration".equals(label)) {
request.setAttribute("action", "AddRU");
gotoServlet("/customerprocessinput", request, response);
} else if ("Feedback".equals(label)) {
request.setAttribute("action", "UpdateSI");
gotoServlet("/customerprocessinput", request, response);
} else {
}
} else {
label = request.getParameter("CustFacility");
if (label != null) {
if ("Register With Us".equals(label)) {
gotoJSPPage("/WEB-INF/jsp/Registration.jsp", request, response);
} else if ("Feedback Form".equals(label)) {
gotoJSPPage("/WEB-INF/jsp/Feedback.jsp", request, response);
} else if ("Product Search".equals(label)) {
gotoJSPPage("/WEB-INF/jsp/ProductSearch.jsp", request, response);
}
}
}
}
// go to requested Servlet
public void gotoServlet(String pageName, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(pageName);
dispatcher.forward(request, response);
}
// go to requested JSP page
public void gotoJSPPage(String pageName, ServletRequest request, ServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(pageName);
dispatcher.forward(request, response);
}
public String gerServletInfo() {
return "A servlet that checks customer facility passed and processes and redirects appropriately";
}
}
Compiling Our Source File With the -cp
and -d
Options
Open your command line editor:
Change to directory cd c:\_ServletsJSP_Case_Study\bstrader\src\controller
Compile CusomerFacilities.java
using the java compiler with the -cp
and -d
options as below, making sure you change apache-tomcat-6.0.37
to wherever you downloaded Tomcat to.
javac -cp c:\apache-tomcat-6.0.37\lib\servlet-api.jar -d ..\..\classes CustomerFacilities.java
The following screenshot shows that we get a clean compile and also the CusomerFacilities
class is now compiled into the classes\controller
directory.
Compiling The CustomerProcessInput
ClassTop
After control is dispatched to the relevant module via the front controller if the database needs to be accessed to populate the view, or to action user input, then control is passed to the CustomerProcessInput
Java servlet class which calls the CustomerDBAccess
Java servlet class with the appropriate parameters for deletion/insertion/modificatiom/retrieval of data.
Cut and paste the following code into your text editor and save it in the c:\_ServletsJSP_Case_Study\bstrader\src\controller directory as CustomerProcessInput.java
.
package controller;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import model.CustomerDBAccess;
public class CustomerProcessInput extends HttpServlet {
private static final long serialVersionUID = 1L;
// Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
// Decide which database record to access
String action = (String) request.getAttribute("action");
if (action != null) {
if ("GetSI".equals(action)) {
processSI(action, session, request, response);
} else if ("GetBSLocDiary".equals(action)) {
processBSLocDiary(action, session, request, response);
} else if ("GetSIRU".equals(action)) {
processSIRU(action, session, request, response);
} else if ("ShowRUForm".equals(action)) {
gotoJSPPage("/WEB-INF/jsp/Registration.jsp", request, response);
}
}
}
// Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
// Decide which database record to update
String action = (String) request.getAttribute("action");
if (action != null) {
if ("AddRU".equals(action)) {
processRU(action, request, response);
} else if ("UpdateSI".equals(action)) {
processUpdateSI(action, session, request, response);
}
}
}
// process stock item action for Get
public void processSI(String action, HttpSession session, ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
// Get all stock item records
CustomerDBAccess cdba = new CustomerDBAccess();
try {
cdba.connect();
} catch(Exception e) {
System.out.println("Problem opening the database" + e);
request.setAttribute("action", "GetSI");
request.setAttribute("label", "Product Search");
writer.print("<html><head><title>Open Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem opening the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Product+Search'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
try {
ResultSet rs = cdba.getSIFields();
int count = 0;
String[] stockName = new String[50];
String[] selectCat = new String[50];
String[] stockDesc = new String[50];
String[] stockPrice = new String[50];
String[] stockLevel = new String[50];
String[] stockReorderLevel = new String[50];
String[] stockSoldLastBootsale = new String[50];
String[] customerName = new String[50];
String[] feedbackText = new String[50];
String[] feedbackRating = new String[50];
while(rs.next()) {
stockName[count] = rs.getString("stockname");
selectCat[count] = rs.getString("stockitemcategory");
stockDesc[count] = rs.getString("stockitemdescription");
stockPrice[count] = rs.getString("stockprice");
stockLevel[count] = rs.getString("stockLevel");
stockReorderLevel[count] = rs.getString("stockreorderlevel");
stockSoldLastBootsale[count] = rs.getString("stocksoldlastbootsale");
customerName[count] = rs.getString("customername");
feedbackText[count] = rs.getString("feedbacktext");
feedbackRating[count] = rs.getString("feedbackrating");
count ++;
}
session.setAttribute("siStockName", stockName);
session.setAttribute("siSelectCat", selectCat);
session.setAttribute("siStockDesc", stockDesc);
session.setAttribute("siStockPrice", stockPrice);
session.setAttribute("siStockLevel", stockLevel);
session.setAttribute("siStockReorderLevel", stockReorderLevel);
session.setAttribute("siStockSoldLastBootsale", stockSoldLastBootsale);
session.setAttribute("siCustomerName", customerName);
session.setAttribute("siFeedbackText", feedbackText);
session.setAttribute("siFeedbackRating", feedbackRating);
session.setAttribute("countsinames", -- count);
} catch (SQLException e) {
request.setAttribute("action", "GetSI");
request.setAttribute("label", "Product Search");
writer.print("<html><head><title>Reading Stock Item Record</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>SQLException: fail reading stockitem database record." +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Product+Search'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
try {
cdba.disconnect();
} catch(Exception e) {
System.out.println("Problem closing the database" + e);
request.setAttribute("action", "GetSI");
request.setAttribute("label", "Product Search");
writer.print("<html><head><title>Close Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem closing the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Product+Search'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
String label = (String) request.getAttribute("label");
if ("Product Search".equals(label)) {
gotoJSPPage("/WEB-INF/jsp/ProductSearch.jsp", request, response);
} else if ("Best Sellers".equals(label)) {
gotoJSPPage("/WEB-INF/jsp/BestSellers.jsp", request, response);
}
}
// process bootsale location/diary action for get
public void processBSLocDiary(String action, HttpSession session, ServletRequest request,
ServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
// Get all boot sale location records
CustomerDBAccess cdba = new CustomerDBAccess();
try {
cdba.connect();
} catch(Exception e) {
System.out.println("Problem opening the database" + e);
request.setAttribute("action", "GetBSLocDiary");
request.setAttribute("label", "BootSale Information");
writer.print("<html><head><title>Open Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem opening the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=BootSale+Information'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
try {
// Get all boot sale location records
ResultSet rs = cdba.getBSLocFields();
int count;
count = 0;
String[] locNames = new String[50];
String[] locAddr1 = new String[50];
String[] locAddr2 = new String[50];
String[] locAddr3 = new String[50];
String[] locAddr4 = new String[50];
String[] locPostCode = new String[50];
while(rs.next()) {
locNames[count] = rs.getString("name");
locAddr1[count] = rs.getString("address1");
locAddr2[count] = rs.getString("address2");
locAddr3[count] = rs.getString("address3");
locAddr4[count] = rs.getString("address4");
locPostCode[count] = rs.getString("postcode");
count ++;
}
session.setAttribute("bslocNames", locNames);
session.setAttribute("bslocAddr1", locAddr1);
session.setAttribute("bslocAddr2", locAddr2);
session.setAttribute("bslocAddr3", locAddr3);
session.setAttribute("bslocAddr4", locAddr4);
session.setAttribute("bslocPostCode", locPostCode);
session.setAttribute("countlocnames", -- count);
} catch (SQLException e) {
request.setAttribute("action", "GetBSLocDiary");
request.setAttribute("label", "BootSale Information");
writer.print("<html><head><title>Reading BootSale Location Record</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>SQLException: fail reading bootsalelocation database record." + e +
"<h3><a href='/bstrader/customerfacilities?CustFacility=BootSale+Information'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
// Get all boot sale diary records
try {
ResultSet rs = cdba.getBSDiaryFields();
int count;
count = 0;
String[] dates = new String[50];
String[] locNames = new String[50];
while(rs.next()) {
String date = rs.getString("Date");
// Format date to DD/MM/YYYY for display
String dateDDMMYYYY = date.substring(8,10) + "/" + date.substring(5,7) + "/" + date.substring(0,4);
dates[count] = dateDDMMYYYY;
locNames[count] = rs.getString("name");
count ++;
}
session.setAttribute("bsdDates", dates);
session.setAttribute("bsdLocNames", locNames);
session.setAttribute("countbsdDates", -- count);
} catch (SQLException e) {
request.setAttribute("action", "GetBSLocDiary");
request.setAttribute("label", "BootSale Information");
writer.print("<html><head><title>Reading BootSale Diary Record</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>SQLException: fail reading bootsalediary database record." + e +
"<h3><a href='/bstrader/customerfacilities?CustFacility=BootSale+Information'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
try {
cdba.disconnect();
} catch(Exception e) {
System.out.println("Problem closing the database" + e);
request.setAttribute("action", "GetBSLocDiary");
request.setAttribute("label", "BootSale Information");
writer.print("<html><head><title>Close Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem closing the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=BootSale+Information'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
gotoJSPPage("/WEB-INF/jsp/BootSaleInfo.jsp", request, response);
}
// process stock item/registered action for Get
public void processSIRU(String action, HttpSession session, ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
// Get all stock item records
CustomerDBAccess cdba = new CustomerDBAccess();
try {
cdba.connect();
} catch(Exception e) {
System.out.println("Problem opening the database" + e);
request.setAttribute("action", "ShowRUForm");
request.setAttribute("label", "Register With Us");
writer.print("<html><head><title>Open Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem opening the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Register+With+Us'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
try {
ResultSet rs = cdba.getSIFields();
int count = 0;
String[] stockName = new String[50];
while(rs.next()) {
stockName[count] = rs.getString("stockname");
count ++;
}
session.setAttribute("siStockName", stockName);
session.setAttribute("countsinames", -- count);
} catch (SQLException e) {
request.setAttribute("action", "ShowRUForm");
request.setAttribute("label", "Register With Us");
writer.print("<html><head><title>Reading Stock Item Record</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>SQLException: fail reading stockitem database record." + e +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Register+With+Us'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
// Get all registered user records
try {
ResultSet rs = cdba.getRUserFields();
int count = 0;
String[] rumail = new String[50];
String[] runame = new String[50];
while(rs.next()) {
rumail[count] = rs.getString("email");
runame[count] = rs.getString("forename");
count ++;
}
session.setAttribute("ruEmail", rumail);
session.setAttribute("ruName", runame);
session.setAttribute("countrunames", -- count);
} catch (SQLException e) {
request.setAttribute("action", "ShowRUForm");
request.setAttribute("label", "Register With Us");
writer.print("<html><head><title>Reading Registered User Record</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>SQLException: fail reading registereduser database record." + e +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Register+With+Us'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
try {
cdba.disconnect();
} catch(Exception e) {
System.out.println("Problem closing the database" + e);
request.setAttribute("action", "ShowRUForm");
request.setAttribute("label", "Register With Us");
writer.print("<html><head><title>Close Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem closing the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Register+With+Us'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
gotoJSPPage("/WEB-INF/jsp/Feedback.jsp", request, response);
}
// process registered user action for Post
public void processRU(String action, ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
// Add a registereduser record
CustomerDBAccess cdba = new CustomerDBAccess();
try {
cdba.connect();
} catch(Exception e) {
System.out.println("Problem opening the database" + e);
request.setAttribute("action", "ShowRUForm");
request.setAttribute("label", "Register With Us");
writer.print("<html><head><title>Open Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem opening the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Register+With+Us'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
String email = request.getParameter("email");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String houseName = request.getParameter("houseName");
String streetName = request.getParameter("streetName");
String townName = request.getParameter("townName");
String countyName = request.getParameter("countyName");
String postCode = request.getParameter("postCode");
try {
cdba.addRUser(email, firstName, lastName, houseName, streetName, townName, countyName, postCode);
request.setAttribute("subsequent", "subsequent");
gotoJSPPage("/WEB-INF/jsp/Registration.jsp", request, response);
} catch (SQLException e) {
request.setAttribute("action", "ShowRUForm");
request.setAttribute("label", "Register With Us");
writer.print("<html><head><title>Adding Registered User Record</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>SQLException: fail adding registereduser database record." + e +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Register+With+Us'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
try {
cdba.disconnect();
} catch(Exception e) {
System.out.println("Problem closing the database" + e);
request.setAttribute("action", "ShowRUForm");
request.setAttribute("label", "Register With Us");
writer.print("<html><head><title>Close Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem closing the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Register+With+Us'>" +
"Return to Registered User Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
}
// process stock item feedback update action for Post
public void processUpdateSI(String action, HttpSession session, ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
// Add Feedback to Stock Item record
CustomerDBAccess cdba = new CustomerDBAccess();
try {
cdba.connect();
} catch(Exception e) {
System.out.println("Problem opening the database" + e);
request.setAttribute("action", "GetSIRU");
request.setAttribute("label", "Feedback Form");
writer.print("<html><head><title>Open Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem opening the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Feedback+Form'>" +
"Return to Feedback Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
String stockName = request.getParameter("productName");
String customerName = request.getParameter("firstName");
String feedbackText = request.getParameter("feedbackText");
String feedbackRating = request.getParameter("feedbackRating");
try {
cdba.modifySI(stockName, customerName, feedbackText, feedbackRating);
request.setAttribute("subsequent", "subsequent");
gotoJSPPage("/WEB-INF/jsp/Feedback.jsp", request, response);
} catch (SQLException e) {
request.setAttribute("action", "GetSIRU");
request.setAttribute("label", "Feedback Form");
writer.print("<html><head><title>Stock Item Record Modified</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>SQLException: modify failed for stock item name: " + stockName + "</p>" +
"<p>SQLException was: " + e + "</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Feedback+Form'>" +
"Return to Feedback Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
try {
cdba.disconnect();
} catch(Exception e) {
System.out.println("Problem closing the database" + e);
request.setAttribute("action", "GetSIRU");
request.setAttribute("label", "Feedback Form");
writer.print("<html><head><title>Close Database</title></head>" +
"<body><h3>Error Report</h3>" +
"<p>Database Connection Issue: Problem closing the database</p>" +
"<h3><a href='/bstrader/customerfacilities?CustFacility=Feedback+Form'>" +
"Return to Feedback Page</a></h3>" +
"<h3><a href='/bstrader/home.html'>Return to Home Page</a></h3>" +
"</body></html>");
}
}
public String toString(int number) {
return ("" + number);
}
// go to requested Servlet
public void gotoServlet(String pageName, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(pageName);
dispatcher.forward(request, response);
}
// go to requested JSP facilities page
public void gotoJSPPage(String pageName, ServletRequest request, ServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(pageName);
dispatcher.forward(request, response);
}
public String gerServletInfo() {
return "A servlet that checks trader facility button pressed and redirects appropriately";
}
}
Compiling Our Source File With the -cp
and -d
Options
Open your command line editor:
Change to directory cd c:\_ServletsJSP_Case_Study\bstrader\src\controller
Compile CustomerProcessInput.java
using the java compiler with the -cp
and -d
options as below, making sure you change apache-tomcat-6.0.37
to wherever you downloaded Tomcat to.
javac -cp c:\apache-tomcat-6.0.37\lib\servlet-api.jar;..\..\classes -d ..\..\classes CustomerProcessInput.java
The following screenshot shows that we get a clean compile and also the CustomerProcessInput
class is now compiled into the classes\controller
directory.
Lesson 9 Complete
In this lesson we took a final look at the controller part of the MVC paradigm and coded the controller components for visitors.
What's Next?
In the next lesson we wrap up the case study and test it out.