ZeePedia buy college essays online


Web Design and Development

<<< Previous JAVA: MVC + Case Study Next >>>
 
img
Web Design & Development ­ CS506
VU
Lesson 39
MVC + Case Study
We have covered an adequate amount of Servlets and JSPs in detail. Now, the time has come to learn
different architectures that are most commonly used for the sake of web development. These architectures
also help us to understand where these components best fit in. In this handout, we'll cover the most widely
used/popular architecture i.e. Model View Controller (MVC).
A small case study "Address Book" is also part of this handout that is based on MVC Model 1. Before
moving on to MVC, let's see what error pages are and how they are used?
Error Page
Error Pages enables you to customize error messages. You can even hide them from the user's view
entirely, if you want. This also makes possible to maintain a consistent look and feel throughout an
application, even when those dreaded error messages are thrown.
By means of page directive, a JSP can be given the responsibility of an Error page. An Error JSP is called
by the web server when an uncaught exception gets occurred. This exception is passed as an instance of
java.lang.Throwable to Error JSP (also accessible via implicit exception object).
Defining and Using Error Pages
isErrorPage attribute of a page directive is used to declare a JSP as an error
page.
JSP pages are informed about the error page by setting errorPage attribute of page directive
In the figure below, error.jsp is defined as JSP Error page and index.jsp is informed to call error.jsp if any
uncaught exception rose. This is done by setting attributes errorPage and isErrorPage of the page
directive on these JSPs.
index.jsp
error.jsp
Case Study ­ Address Book
What we have learned is going to be implemented in this Address Book example. Here MS-Access is being
293
img
Web Design & Development ­ CS506
VU
. PersonDAO
­ Encapsulates database logic.
­ Therefore, it will be used to save and retrieve PersonInfo data.
. Java Server Pages
. addperson.jsp
­ Used to collect new person info that will be saved in database.
. saveperson.jsp
­ Receives person info from addperson.jsp
­ Saves it to database
. searchperson.jsp
­ Used to provide search criteria to search Person's info by providing name .
showperson.jsp
­ This page receive person's name from searchperson.jsp to search in database
­ Retrieves and displays person record found against person name
Error Page
.  addbookerror.jsp
­ This page is declared as an error page and used to identify the type of exception.
­ In addition to that, it also displays the message associated with the received exception to the user.
Program Flow
Now let's discuss the flow of program. Assume that the system has been deployed on a JSP compatible
Web Server like Tomcat and has been ready to use for clients. The following figure helps to understand the
program flow of this small example.
addperson.jsp takes person's information from the user and sends it to flow oflow oflowError Page ormation (e'.l 1 Tf
294
img
Web Design & Development ­ CS506
VU
Code for the Case Study
Let's have a look on the code of each component used in the case study; first start from
JavaBeans.
PersonInfo
PersonInfo represents the record of one person and its objects are used to interrupt the information about
persons.
package vu;
import java.io.*;
public class PersonInfo implements Serializable{
private String name;
private String address;
private int phoneNum;
// no argument constructor
public PersonInfo() {
name = "";
address = "";
phoneNum = 0;
}
// setters
public void setName(String n){
name = n;
}
public void setAddress(String a){
address = a;
}
public void setPhoneNum(int pNo){
phoneNum = pNo;
}
// getters
public String getName( ){
return name;
}
public String getAddress( ){
return address;
}
public int getPhoneNum( ){
return phoneNum;
}
} // end class PersonInfo
PersonDAO This class will help in retrieving and storing person's records in database.
The code is given below:
package vu; import java.util.*;
import java.sql.*;
public class PersonDAO{
private Connection con;
295
img
Web Design & Development ­ CS506
VU
// default constructor
public PersonDAO() throws ClassNotFoundException , SQLException { establishConnection(); }
// method used to establish connection with db
private void establishConnection() throws ClassNotFoundException , SQLException {
// establishing conection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conUrl = "jdbc:odbc:PersonDSN";
con = DriverManager.getConnection(conUrl);
}
// used to search the person records against name and returns
// the ArrayList that contains only those PersonInfo objects
// which matches the search criteria i.e. name
public ArrayList retrievePersonList(String Name) throws SQLException {
ArrayList personList = new ArrayList();
// preparing query
String sql = " SELECT * FROM Person WHERE name = ?";
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setString( 1, pName);
// executing query
ResultSet rs = pStmt.executeQuery();
String name;
String add;
int pNo;
while ( rs.next() ) {
name = rs.getString("name");
add = rs.getString("address");
pNo = rs.getInt("phoneNumber");
// creating a CourseOutlineBean object
PersonInfo personBean = new PersonInfo();
personBean.setName(name);
personBean.setAddress(add);
personBean.setPhoneNum(pNo);
// adding a bean to arraylist
personList.add(personBean);
} // end while
return personList;
} // end retrievePersonList
// this method accepts an object of PersonInfo, and stores it into  // the database
public void
addPerson(PersonInfo person) throws SQLException{
String sql = " INSERT INTO Person VALUES (?, ?, ?)";
PreparedStatement pStmt = con.prepareStatement(sql);
String name = person.getName();
String add = person.getAddress();
296
img
Web Design & Development ­ CS506
VU
int pNo = person.getPhoneNum();
pStmt.setString( 1 , name );
pStmt.setString( 2 , add );
pStmt.setInt( 3 , pNo );
pStmt.executeUpdate();
} // end addPerson
// overriding finalize method to release acquired resources
public void finalize( ) {
try{
if(con != null){
con.close();
}
}catch(SQLException sqlex){
System.out.println(sqlex);
}
} // end finalize
} // end PersonDAO class
Now let's take a look at the code for JSP pages
addperson.jsp
This JSP page gets person record's information from the user. It contains three Input
Fields for name, address and phone number as shown in the diagram. This page sends this information to
saveperson.jsp for further processing,
The code that is used to generate the above page is given below:
<%-- Although there are no chances of exception to arise on this page, for consistency, error
page is defined on top of all JSPs
--%>
<%@page errorPage="addbookerror.jsp" %>
297
img
Web Design & Development ­ CS506
VU
<html> <body>
<center>
<h2> Address Book </h2>
<h3> Add New Person</h3>
<%-- Form that contains Text input fields and sending it to
saveperson.jsp --%>
<form name ="register" action="saveperson.jsp" />
<TABLE BORDER="1" >
<TR>
<TD> <h4 > Name </h4> </TD>
<TD> <input type="text" name="name" /> </TD>
</TR>
<TR>  <TD> <h4> Address </h4>  </TD>
<TD> <input type="text" name="address" /> </TD>
</TR>
<TR>  <TD> <h4>Phone Number</h4>  </TD>
<TD> <input type="text" name="phoneNum" /> </TD>
</TR>
<TR>  <TD COLSPAN="2" ALIGN="CENTER" >
<input type="submit" value="save" /><input type="reset"
value="clear" />
</TD>
</TR>
</TABLE>
</form>
<h4>
<%-- A link to searchperson.jsp --%>
<a href="searchperson.jsp" > Search Person </a>
</h4>
</center>
</body>
</html>
saveperson.jsp
This JSP page gets data from the addperson.jsp, makes an object of PersonInfo and saves it to the database
using PersonDAO class. Apart from these, it also displays an informative message to the user if new person
record is saved successfully into the database and two hyperlinks to navigate on to the desired pages as
shown in the following diagram:
The code of this page is given
below:
<%-- defining error page --%>
<%@page
errorPage="addbookerror.jsp"
%>
<%@ page import="java.sql.*"
%>
<html>
<body>
<%-- creating PersonDAO
object and storing in page scope --%>
298
img
Web Design & Development ­ CS506
VU
<jsp:useBean id="pDAO" class="vu.PersonDAO" scope="page" />
<%-- creating PersonBean object and storing in page scope --%>
<jsp:useBean id="personBean" class="vu.PersonInfo" scope = "page" />
<%--
setting all properties of personBean object with input
parameters using *
--%>
<jsp:setProperty name="personBean" property="*" />
<%--
to save Person record into the database, calling addperson
method of PersonDAO
--%>
<%
pDAO.addPerson(personBea
n);
%>
<center>
<h3> New Person Record is saved successfully!</h3>
<h4>
<a href="addperson.jsp" > Add Person </a>
</h4>
<h4>
<a href="searchperson.jsp" > Search Person </a>
</h4>
</center>
</body>
</html>
searchperson.jsp
It gets search criteria from the user (i.e. name) and sends it to showperson.jsp to display the search results.
The outlook of the page is given below:
The code used to generate the above page given page is:
<%-- defining error page --%>
<%@page errorPage="addbookerror.jsp" %>
<html> <body>
299
img
Web Design & Development ­ CS506
VU
<center>
<h2> Address Book </h2>
<h3> Search Person</h3>
<%-- Form that contains Text input field and sending it to showperson.jsp
--%>
<form name ="search" action="showperson.jsp" />
<TABLE BORDER="1" >
<TR>
<TD> <h4 >Name</h4> </TD>
<TD> <input type="text" name="name" /> </TD>
</TR>
<TR> <TD COLSPAN="2" ALIGN="CENTER"">
<input type="submit" value="search" /><input type="reset" value="clear"
/>
</TD>
</TR>
</TABLE>
</form>
<h4>
<a href="addperson.jsp" > Add Person </a>
</h4>
</center></body>
</html>
showperson.jsp
showperson.jsp receives search criteria (i.e. name) from the searchperson.jsp, that is entered by the user to
find the matching record. This page retrieves the complete list of matching records from the database using
PersonDAO, and shows them to the user.
This following figure gives you the sight, when person named "saad" is searched.
Below, the code of showperson.jsp is given:
<%-- defining error page --%>
<%@page errorPage="addbookerror.jsp" %>
<%-- importing required packages --%>
<%@page import="java.util.*" %>
<%@page import="vu.*" %>
<html>
<body>
300
img
Web Design & Development ­ CS506
VU
<center>
<h2> Address Book </h2>
<h3> Following results meet your search criteria</h3>
<TABLE BORDER="1" >
<TR>
<TH> Name </TH>
<TH> Address </TH>
<TH> PhoneNum </TH>
</TR>
<jsp:useBean id="pDAO" class="vu.PersonDAO" scope="page" />
<%
// getting search criteria sent by searchperson.jsp
String pName = request.getParameter("name");
// retrieving matching records from the Database using // retrievePersonList() method of
PersonDAO
ArrayList personList = personDAO.retrievePersonList(pName);
PersonInfo person = null;
// Showing all matching records by iterating over ArrayList
for(int i=0; i<personList.size(); i++) {
person = (PersonInfo)personList.get(i);
%>
<TR> <TD> <%= person.getName()%> </TD>
<TD> <%=
person.getAddress()%> </TD>
<TD> <%= person.getPhoneNum()%> </TD>
</TR>
<%
} // end for
%>
</TABLE >
<a href="addperson.jsp" > Add Person </a>
<a href="searchperson.jsp" > Search Person </a>
</center>
</body>
</html>
addbookerror.jsp
This JSP error page is called implicitly by all other JSP pages whenever any uncaught / unhandled
exception occurs. It also finds out the type of the exception that is generated, and shows an appropriate
message to the user:
<%-- indicating that this is an error page --%>
<%@page isErrorPage="true" %>
<%-- importing class --%>
<%@page import = "java.sql.SQLException" %>
<html>
<head>  <title>Error</title>  </head>
<body>
<h2>
Error Page
</h2>
301
img
Web Design & Development ­ CS506
VU
<h3>
<%-- scriptlet to determine exception type --%>
<%
if (exception instanceof SQLException) {
%>
An SQL Exception
<%
} else if (exception instanceof ClassNotFoundException){
%>
A Class Not Found Exception
<%
} else {
%>
A Exception
<%
} // end if-else
%>
<%-- end scriptlet to determine exception type --%>
occured while interacting with the database
</h3>
<h3>
The Error Message was
<%= exception.getMessage() %>
</h3>
<h3 > Please Try Again Later! </h3>
<%-- hyperlinks to return back to addperson.jsp or searchperson.sjp
--%>
<h3>
<a href="controller.jsp?action=addperson" > Add Person
</a>
<a href="controller.jsp?action=searchperson" > Search Person
</a>
</h3>
</body>
</html>
Model View Controller (MVC)
Now, more than ever, enterprise applications need to support multiple types of users with multiple
types of interfaces. For example, an online store may require an HTML front for Web customers, a
TM
(JFC) / Swing interface for administrators, and an
WML front for wireless customers, a Java
XML-based Web service for suppliers
302
img
Web Design & Development ­ CS506
VU
Also, several problems can arise when applications contain a mixture of data access code, business logic
code, and presentation code. Such applications are difficult to maintain, because interdependencies between
all of the components cause strong ripple effects whenever a change is made anywhere. High coupling
makes classes difficult or impossible to reuse because they depend on so many other classes. Adding new
data views often requires re-implementing or cutting and pasting business logic code, which then requires
maintenance in multiple places. Data access code suffers from the same problem, being cut and pasted
among business logic methods.
The Model-View-Controller architecture solves these problems by decoupling data access, business logic,
and data presentation and user interaction. Such separation allows multiple views to share the same
enterprise data model, which makes supporting multiple clients easier to implement, test, and maintain.
Participants and Responsibilities
The individual's responsibility of three participants (model, view & controller) is given
below:
. Model
The model represents the state of the component (i.e. its data and the methods required to manipulate it)
independent of how the component is viewed or rendered.
. View
The view renders the contents of a model and specifies how that data should be presented. There can be
multiple views for the same model within single applications or model may have different views in
different applications or operating systems.
. Controller
The controller translates interactions with the view into actions to be performed by the model. In a web
application, they appear as GET and POST HTTP requests. The actions performed by the model
include activating business processes or changing the state of the model. Based on the user interactions
and the outcome of the model actions, the controller responds by selecting an appropriate view.
Evolution of MVC Architecture
In the beginning, we used no MVC. Then we had MVC Model 1 and MVC Model 2 architectures. And
people came up with so called web application frameworks such as Apache Struts based on Model 2
architecture. And finally we have a standard web based application framework i.e. JavaServer Faces (JSF).
In this handout, we'll only talk about MVC Model 1.
MVC Model 1
A Model 1 architecture consists of a Web browser directly accessing Web-tier JSP pages. The JSP pages
303
img
Web Design & Development ­ CS506
VU
access JavaBeans that represent the application model. And the next view
to display (JSP page, servlet, HTML page, and so on) is determined either by hyperlinks selected in the
source document or by request parameters.
In Model 1 architecture, view selection is decentralized, because the current page being displayed
determines the next page to display. In addition, each JSP page or servlet processes its own inputs
(parameters from GET or POST). And this is hard to maintain, for example, if you have to change the view
selection, then several JSP pages need to be changed. In some Model 1 architectures, choosing the next
page to display occurs in scriptlet code, but this usage is considered poor form.
In MVC Model 1 architecture, the JSP page alone is responsible for processing the incoming request and
replying back to the client. There is still separation of presentation from content, because all data access is
performed using JavaBeans.
Although the Model 1 architecture should be perfectly suitable for simple applications, it may not be
desirable for complex implementations. Random usage of this architecture usually leads to a significant
amount of scriptlets or Java code embedded within the JSP page, especially if there is a significant amount
of request processing to be performed. While this may not seem to be much of a problem for Java
developers, it is certainly an issue if your JSP pages are created and maintained by designers which are only
aware of HTML and some scripting language.
Note: Probably some of you must be thinking about the case study discussed earlier in this handout.
Indeed, it is based on MVC Model 1 architecture.
References:
Java A Lab Course by Umair Javed
Java BluePrints - J2EE Patterns
http://java.sun.com/blueprints/patterns/MVC-detailed.html
Exploring the MVC Design Pattern
http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html
304