Advanced Programming and Technologies
Assignment: Contact Book Application with JDBC, Servlets, and JSP
Module Code: CS5054NT
Module Leader: Binay Koirala (
[email protected])
Module Tutor: Sujan Subedi (
[email protected])
1. Introduction
In this assignment, you will develop a basic Contact Book Application that allows users to store and
manage their contacts. You will implement the fundamental CRUD (Create, Read, Update, Delete)
operations using JDBC for database connectivity, and create a simple user interface using Servlets and
JSP.
This project will help you understand:
How web applications interact with databases
The MVC (Model-View-Controller) architectural pattern
Basic web application development in Java
1.1 Learning Objectives
By completing this assignment, you will be able to:
Implement the MVC architecture in a Java web application
Use JDBC to connect to and manipulate a database
Create Servlets as controllers to handle user requests
Design JSP pages to display information to users
Apply CRUD operations in a practical application
2. The MVC Architecture
The MVC (Model-View-Controller) pattern is a design pattern that separates an application into three
main components:
2.1 Model
Represents the data and business logic
Handles data storage, retrieval, and validation
Communicates with the database
In this assignment: Java classes that represent contacts and handle database operations
2.2 View
Presents the data to users
Handles the user interface
In this assignment: JSP pages that display forms and contact information
2.3 Controller
Processes user input
Coordinates between Model and View
In this assignment: Servlets that handle HTTP requests and responses
3. Project Requirements
3.1 Functional Requirements
Your Contact Book Application must include the following features:
1. Contact Management
Add new contacts with basic details (name, phone, email, address)
View a list of all saved contacts
View details of a specific contact
Update contact information
Delete contacts
Search for contacts by name
2. User Interface
A clean, easy-to-use interface for all operations
Forms for adding and updating contacts
Confirmation before deleting contacts
3.2 Technical Requirements
1. Database
Use MySQL database
Create a table for storing contact information
Implement appropriate constraints
2. Application Structure
Strictly follow the MVC architecture with three packages:
model : Contact class and database operations
view : JSP pages
controller : Servlet classes
3. Java Technologies
JDBC for database connectivity
Servlets for handling HTTP requests
JSP for the user interface and basic CSS for styling
4. Project Structure
Organize your project with the following structure:
ContactBookApp/
├── src/
│ └── main/
│ ├── java/
│ │ ├── model/
│ │ │ ├── Contact.java
│ │ │ └── ContactDAO.java
│ │ └── controller/
│ │ └── ContactServlet.java
│ └── webapp/
│ ├── WEB-INF/
│ │ └── web.xml
│ ├── view/
│ │ ├── contact-list.jsp
│ │ ├── add-contact.jsp
│ │ ├── edit-contact.jsp
│ │ └── view-contact.jsp
│ └── css/
│ └── style.css
└── pom.xml (or build.gradle)
5. Implementation Guide
5.1 Database Setup
First, create your database and the contacts table:
CREATE DATABASE contactbook;
USE contactbook;
CREATE TABLE contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
phone VARCHAR(20),
email VARCHAR(100),
address VARCHAR(255)
);
5.2 Model Layer
The Model layer will consist of two main components:
1. Contact Class: Represents the data structure
package model;
public class Contact {
private int id;
private String name;
private String phone;
private String email;
private String address;
// Constructor, getters and setters
// ...
}
2. ContactDAO (Data Access Object): Handles database operations
package model;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ContactDAO {
private Connection connection;
// Constructor that establishes database connection
public ContactDAO() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/contactbook",
"username", "password");
} catch (Exception e) {
e.printStackTrace();
}
}
// Example method for adding a contact
public void addContact(Contact contact) {
try {
String sql = "INSERT INTO contacts (name, phone, email, address) VALUES (?, ?, ?, ?)"
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, contact.getName());
statement.setString(2, contact.getPhone());
statement.setString(3, contact.getEmail());
statement.setString(4, contact.getAddress());
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Add other methods for:
// - getContactById(int id)
// - getAllContacts()
// - updateContact(Contact contact)
// - deleteContact(int id)
// - searchContacts(String name)
}
5.3 Controller Layer
The Controller layer will consist of servlets that handle HTTP requests:
package controller;
import model.Contact;
import model.ContactDAO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/contacts/*")
public class ContactServlet extends HttpServlet {
private ContactDAO contactDAO;
public void init() {
contactDAO = new ContactDAO();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getPathInfo();
if (action == null) {
action = "/list";
}
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/delete":
deleteContact(request, response);
break;
case "/view":
viewContact(request, response);
break;
default:
listContacts(request, response);
break;
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getPathInfo();
if (action == null) {
action = "/list";
}
switch (action) {
case "/insert":
insertContact(request, response);
break;
case "/update":
updateContact(request, response);
break;
default:
listContacts(request, response);
break;
}
}
// Implement each action method:
// - listContacts(request, response)
// - showNewForm(request, response)
// - showEditForm(request, response)
// - insertContact(request, response)
// - updateContact(request, response)
// - deleteContact(request, response)
// - viewContact(request, response)
}
5.4 View Layer
The View layer will consist of JSP pages:
contact-list.jsp (Example snippet):
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Contact Book</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<div class="container">
<h1>Contact List</h1>
<div class="search-box">
<form action="contacts/list" method="get">
<input type="text" name="search" placeholder="Search by name...">
<button type="submit">Search</button>
</form>
</div>
<a href="contacts/new" class="btn">Add New Contact</a>
<table>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Actions</th>
</tr>
<c:forEach var="contact" items="${contactList}">
<tr>
<td><c:out value="${contact.name}" /></td>
<td><c:out value="${contact.phone}" /></td>
<td><c:out value="${contact.email}" /></td>
<td>
<a href="contacts/view?id=<c:out value='${contact.id}' />">View</a>
<a href="contacts/edit?id=<c:out value='${contact.id}' />">Edit</a>
<a href="contacts/delete?id=<c:out value='${contact.id}' />"
onclick="return confirm('Are you sure you want to delete this contact?
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
6. Step-by-Step Implementation Guide
6.1 Set Up Your Environment
1. Set up a Java development environment (Eclipse, IntelliJ, etc.)
2. Install MySQL and MySQL Workbench
3. Configure your web server (Tomcat, Jetty, etc.)
4. Create a new Dynamic Web Project
6.2 Create the Database
1. Run the SQL script from section 5.1 to create the database and table
6.3 Implement the Model Layer
1. Create the model package
2. Implement the Contact class
3. Implement the ContactDAO class with JDBC functionality
6.4 Implement the Controller Layer
1. Create the controller package
2. Implement the ContactServlet class
3. Define all the required action methods
6.5 Implement the View Layer
1. Create JSP pages in the view folder
2. Add CSS styling
3. Implement forms for adding and editing contacts
4. Create the list view for displaying all contacts
6.6 Test Your Application
1. Deploy the application to your web server
2. Test each CRUD operation
3. Verify that all functional requirements are met
7. Documentation Requirements
Along with your application, you must submit a short documentation (3-5 pages) that includes:
1. Project Overview
Brief description of your application
List of implemented features
2. System Architecture
Description of the MVC pattern implementation
Database schema diagram
3. Screenshots
Include screenshots of all main pages
Include screenshots showing each CRUD operation
4. Testing
Describe the testing process
Document at least 5 test cases with expected and actual results
5. Reflection
Challenges faced and solutions implemented
Learning outcomes
Possible future improvements
8. Key Concepts to Understand
8.1 JDBC (Java Database Connectivity)
JDBC is an API for connecting Java applications to databases. Key components include:
Connection: Establishes a connection to a database
Statement: Used to execute SQL queries
PreparedStatement: A more secure way to execute parameterized SQL queries
ResultSet: Contains data retrieved from a database
8.2 Servlets
Servlets are Java classes that handle HTTP requests and generate responses. Key points:
Extend HttpServlet class
Override doGet() and doPost() methods
Use RequestDispatcher to forward requests to JSP pages
8.3 JSP (JavaServer Pages)
JSP is a technology that allows you to embed Java code in HTML pages. Key features:
HTML-like syntax with Java code embedded in tags
JSTL (JSP Standard Tag Library) for common tasks
Expression Language (EL) for accessing data
8.4 MVC Pattern Benefits
Separation of concerns: Each component has a specific responsibility
Code reusability: Components can be reused in different contexts
Ease of maintenance: Changes to one component don't affect others
Parallel development: Different team members can work on different components
9. Submission Guidelines
1. Code Submission
Create a ZIP file containing your entire project
Include all source files, configuration files, and resources
Do not include compiled class files or .war files
2. Documentation Submission
Submit your documentation as a PDF file
Include a cover page with your name, student ID, and module details
Follow the documentation requirements in section 7
3. Deadline
Submit your assignment by [insert deadline]
Late submissions will be penalized according to university policy
10. Contact Information
If you have any questions or need assistance, please contact:
Name Role Email Office Hours
Binay Koirala Module Leader [email protected] Monday, Wednesday 2-4 PM
Sujan Subedi Module Tutor [email protected] Tuesday, Thursday 1-3 PM
11. Resources and References
12.1 JDBC Resources
Oracle JDBC Tutorial: https://docs.oracle.com/javase/tutorial/jdbc/
JDBC PreparedStatement:
https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html
12.2 Servlet and JSP Resources
Servlet API Documentation: https://javaee.github.io/javaee-spec/javadocs/
JSP Tutorial: https://docs.oracle.com/javaee/5/tutorial/doc/bnagx.html
JSTL Tutorial: https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm
12.3 MVC Pattern Resources
MVC Pattern Overview: https://www.tutorialspoint.com/design_pattern/mvc_pattern.htm
MVC in Java Web Applications: https://www.javatpoint.com/mvc-architecture-in-java
12.4 MySQL Resources
MySQL Documentation: https://dev.mysql.com/doc/
MySQL Connector/J Documentation: https://dev.mysql.com/doc/connector-j/en/
Good luck with your assignment! Remember to start early and ask for help if you need it.