0% found this document useful (0 votes)
5 views16 pages

AdvancedProgrammingandTechnologiesWeek04Tutorialandworkshoptask f9f40f90 5cb2 49db Bda9 1749c7e7bff8 159290

The document outlines a project for developing a Todo Application using Java Servlets, JSP, and JDBC, following the MVC architecture. It includes detailed learning objectives, functionality and technical requirements, project setup instructions, and implementation steps for the model, controller, and view layers. Additionally, it provides hints, tips, and extension ideas for enhancing the application after completing the basic requirements.

Uploaded by

Harry Borth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

AdvancedProgrammingandTechnologiesWeek04Tutorialandworkshoptask f9f40f90 5cb2 49db Bda9 1749c7e7bff8 159290

The document outlines a project for developing a Todo Application using Java Servlets, JSP, and JDBC, following the MVC architecture. It includes detailed learning objectives, functionality and technical requirements, project setup instructions, and implementation steps for the model, controller, and view layers. Additionally, it provides hints, tips, and extension ideas for enhancing the application after completing the basic requirements.

Uploaded by

Harry Borth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Advanced Programming and Technologies

Todo Application Project


Module Name: Advanced Programming and Technologies
Module Leader: Binay Koirala ([email protected])
Module Tutor: Sujan Subedi ([email protected])

Project Description
In this project, you will develop a Todo Application using Java Servlets, JSP, and JDBC. This web
application will allow users to create, view, and delete todo items. The application follows the Model-
View-Controller (MVC) architecture pattern, which separates the application into three main components:

1. Model: Represents the data and business logic


2. View: Displays the data to the user
3. Controller: Handles user input and updates the model and view accordingly

This project will help you understand core web development concepts using Java technologies and
reinforce your understanding of database operations, web application architecture, and user interface
design.

Learning Objectives
By completing this project, you will be able to:

1. Implement a web application using Java Servlets and JSP


2. Apply the MVC architecture pattern in a real-world application
3. Connect a Java application to a MySQL database using JDBC
4. Create, read, and delete operations on a database
5. Design a simple but effective user interface for a web application
6. Handle form submissions and data validation
7. Implement proper error handling in a web application
Project Requirements

Functionality Requirements
Your Todo Application must include the following features:

1. Add Todo: Users should be able to add new todo items with a title, description, and completion
status.
2. View Todos: Users should be able to view a list of all todo items.
3. Delete Todo: Users should be able to delete a todo item.
4. Navigation: Users should be able to navigate between different pages of the application.

Technical Requirements
Your implementation must adhere to the following technical requirements:

1. Java Servlet & JSP: Use Java Servlets for controllers and JSP for views.
2. JDBC: Use JDBC for database operations.
3. MySQL Database: Use a MySQL database to store todo items.
4. MVC Architecture: Follow the MVC architecture pattern.
5. Project Structure: Organize your code in a logical directory structure.
6. Error Handling: Implement proper error handling and display appropriate messages to users.
7. CSS Styling: Apply CSS styling to make the application visually appealing.
Project Setup

Step 1: Setting Up the Development Environment


1. Install Eclipse IDE:

Download and install the latest version of Eclipse IDE for Enterprise Java and Web Developers.
Launch Eclipse and select a workspace location.

2. Install Apache Tomcat:

Download Apache Tomcat (version 10.0 or later) from the official website.
Extract the downloaded file to a location on your computer.

3. Configure Tomcat in Eclipse:

In Eclipse, go to Window > Preferences > Server > Runtime Environments.


Click "Add" and select the appropriate Apache Tomcat version.
Click "Next" and browse to the Tomcat installation directory.
Click "Finish" and then "Apply and Close".

Step 2: Creating a Dynamic Web Project


1. Create a New Project:
Go to File > New > Dynamic Web Project.
Enter "TodoApplication" as the project name.
Select Apache Tomcat as the target runtime.
Set the Dynamic web module version to 6.0.
Check "Generate web.xml deployment descriptor".
Click "Finish".
2. Project Structure:

Your project should have the following structure:

TodoApplication/
├── src/main/java/ # Java source files
│ ├── controller/ # Servlet classes
│ └── model/ # Model classes
├── src/main/webapp/ # Web resources
│ ├── WEB-INF/ # Configuration files
│ ├── assets/ # CSS, JS, and other static files
│ ├── view/ # JSP files
│ └── index.jsp # Home page

3. Adding Required Libraries:

Create a lib folder inside the WEB-INF directory.


Download the MySQL Connector/J JAR file from the official website.
Add the JAR file to the lib folder.
Right-click on the JAR file, select "Build Path" > "Add to Build Path".

Step 3: Setting Up the Database


1. Install MySQL:

Download and install MySQL Server and MySQL Workbench.

2. Create the Database and Table:

Open MySQL Workbench and connect to your local MySQL server.


Execute the following SQL commands to create the database and table:

-- Create the database


CREATE DATABASE todo_database;

-- Use the database


USE todo_database;

-- Create the todo table


CREATE TABLE todo_table (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT,
completed BOOLEAN DEFAULT false
);
Project Implementation

Step 1: Creating the Model Layer


The model layer represents the data and business logic of your application. For this project, you need to
create two classes:

1. TodoModel.java : Represents a todo item with properties like id, title, description, and completed
status.
2. TodoDAO.java : Data Access Object that handles database operations for todo items.
TodoModel.java

package model;

public class TodoModel {


//Instance Variables
private int id; //Primary key
private String title;
private String description;
private boolean completed;

// Constructor with id
public TodoModel(int id, String title, String description, boolean completed) {
this.id = id;
this.title = title;
this.description = description;
this.completed = completed;
}

// Constructor without id (for new todos)


public TodoModel(String title, String description, boolean completed) {
this.title = title;
this.description = description;
this.completed = completed;
}

// Getters and setters


// ... (implement all getters and setters for each field)

@Override
public String toString() {
// Implement toString method
}
}
TodoDAO.java

package model;

import java.sql.*;
import java.util.ArrayList;

public class TodoDAO {


// Database connection parameters
private static final String URL = "jdbc:mysql://localhost:3306/todo_database";
private static final String USER = "root";
private static final String PASSWORD = ""; // Use your actual MySQL password

static {
// Load the MySQL JDBC driver
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Failed to load MySQL driver", e);
}
}

// Method to establish a database connection


public static Connection getConnection(String url, String user, String password)
throws SQLException {
return DriverManager.getConnection(url, user, password);
}

// Method to add a todo to the database


public static int addTodo(TodoModel todoModel) throws SQLException {
// Implement the SQL INSERT statement with PreparedStatement
// Return the generated ID of the new todo item
}

// Method to remove a todo from the database


public static boolean removeTodo(TodoModel todoModel) {
// Implement the SQL DELETE statement with PreparedStatement
// Return true if the deletion was successful, false otherwise
}

// Method to list all todos from the database


public static ArrayList<TodoModel> listTodo() {
// Implement the SQL SELECT statement to retrieve all todos
// Return an ArrayList of TodoModel objects
}
}
Step 2: Creating the Controller Layer
The controller layer handles user input and updates the model and view accordingly. For this project, you
need to create three servlet classes:

1. AddTodoServlet.java : Handles the creation of new todo items.


2. ListTodoServlet.java : Retrieves and displays all todo items.
3. DeleteTodoServlet.java : Handles the deletion of todo items.

AddTodoServlet.java

package controller;

import model.TodoModel;
import model.TodoDAO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/AddTodoServlet")
public class AddTodoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// 1. Retrieve form data (title, description, completed status)

// 2. Create a new TodoModel object with the form data

// 3. Add the todo to the database using TodoDAO

// 4. Redirect to the list page after successful addition or show error message
}
}
ListTodoServlet.java

package controller;

import model.TodoModel;
import model.TodoDAO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/ListTodoServlet")
public class ListTodoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// 1. Retrieve all todos from the database using TodoDAO

// 2. Set the todos as a request attribute

// 3. Forward to the list-todo.jsp page


}
}
DeleteTodoServlet.java

package controller;

import model.TodoModel;
import model.TodoDAO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/DeleteTodoServlet")
public class DeleteTodoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// 1. Retrieve the todo ID from the request parameter

// 2. Create a TodoModel object with the ID

// 3. Delete the todo from the database using TodoDAO

// 4. Redirect to the list page after successful deletion or show error message
}
}
Step 3: Creating the View Layer
The view layer displays the data to the user. For this project, you need to create three JSP files:

1. index.jsp : The home page with links to other pages.


2. add-todo.jsp : The form for adding new todo items.
3. list-todo.jsp : The page that displays all todo items.

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<html>
<head>
<title>Todo Application</title>
<link rel="stylesheet" type="text/css" href="./assets/css/styles.css">
</head>
<body>
<h1>Welcome to the Todo Application</h1>
<hr/>
<p><a href="${pageContext.request.contextPath}/view/add-todo.jsp">Add a new todo</a></p>
<p><a href="${pageContext.request.contextPath}/ListTodoServlet">View all todos</a></p>
<hr/>
</body>
</html>
add-todo.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<html>
<head>
<title>Add Todo</title>
<link rel="stylesheet" type="text/css" href="../assets/css/styles.css">
</head>
<body>
<h1>Add a New Todo</h1>
<hr/>
<form action="../AddTodoServlet" method="post">
<!-- Form fields for title, description, and completed status -->

<input type="submit" value="Add Todo">


</form>
<hr/>
<p><a href="${pageContext.request.contextPath}/index.jsp">Back to Home</a></p>
</body>
</html>
list-todo.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<%@ page import="java.util.List, model.TodoModel" %>
<html>
<head>
<title>Todo List</title>
<style>
<%@ include file="../assets/css/styles.css"%>
</style>
</head>
<body>
<h1>Todo List</h1>
<hr/>
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Completed</th>
<th>Actions</th>
</tr>
<%
// Retrieve todos from request attribute and display them in a table
// Include a delete link for each todo
%>
</table>
<hr/>
<p><a href="${pageContext.request.contextPath}/index.jsp">Back to Home</a></p>
</body>
</html>
Step 4: Adding CSS Styling
Create a CSS file to style your application:

/* src/main/webapp/assets/css/styles.css */
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

body {
font-family: 'Roboto', sans-serif;
background-color: #f9f9f9;
max-width: 800px;
margin: 0 auto;
padding: 40px 20px;
}

h1 {
text-align: center;
}

/* Add more CSS styles for tables, forms, buttons, etc. */

Testing Your Application


1. Running the Application:

Right-click on your project in Eclipse.


Select "Run As" > "Run on Server".
Select the configured Tomcat server.
Click "Finish".

2. Testing Functionality:

Test adding a new todo item.


Test viewing the list of todo items.
Test deleting a todo item.
Test error handling by creating edge cases.
Hints and Tips
1. Understanding MVC:

Model: Represents the data and business logic (TodoModel and TodoDAO).
View: Displays the data to the user (JSP files).
Controller: Handles user input and updates the model and view accordingly (Servlets).

2. JDBC Connection:

Always close database connections, statements, and result sets in a finally block or use try-with-
resources.
Use PreparedStatement to prevent SQL injection attacks.

3. Error Handling:

Catch exceptions and display user-friendly error messages.


Log detailed error information for debugging purposes.

4. JSP Best Practices:

Minimize Java code in JSP files.


Use JSTL when possible (though not required for this project).
Keep your HTML and CSS clean and organized.

5. Debugging:

Use System.out.println() or logging frameworks to debug your application.


Check Tomcat logs for server-side errors.
Extension Ideas
After completing the basic requirements, consider implementing these enhancements to improve your
application:

1. Update Functionality:

Add the ability to update existing todo items.

2. User Authentication:

Implement user registration and login functionality.


Associate todo items with specific users.

3. Sorting and Filtering:

Add options to sort and filter todo items by various criteria.

4. Due Dates:

Add due dates to todo items.


Implement notifications for upcoming due dates.

5. Categories or Tags:

Allow users to categorize todo items or add tags.


Add filtering by categories or tags.

6. Ajax Implementation:

Use Ajax to add, update, and delete todo items without page reloads.

7. Responsive Design:

Enhance the CSS to make the application fully responsive for various screen sizes.

8. Data Validation:

Implement client-side and server-side validation for form inputs.

Advanced Programming and Technologies


Module Leader: Binay Koirala ([email protected])
Module Tutor: Sujan Subedi ([email protected])

You might also like