First assignment--ContactsManagement--832201118--岳文韬

832201118岳文韬 2024-10-31 02:42:12

目录

  • Contact Management System Project
  • 1. Project Overview
  • 1.1 Overview
  • 1.2 Technology Stack
  • 2. GitHub Links
  • 3. PSP Table
  • 4. Feature Demonstration
  • 4.1 Add Contact
  • 4.2 Edit Contact
  • 4.3 Delete Contact
  • 4.4 Phone Number Validation
  • 4.5 Form Completeness Validation
  • 5. Design and Implementation Process
  • 5.1 Front-End
  • 5.2 Back-End
  • 6. Code Analysis
  • 6.1 ContactController: addContact Method
  • 6.2 Contacts.js: saveContact Function
  • 6.3 Contacts.js: loadContacts Function
  • 6.4 Contacts.js: deleteContact Function
  • 7. Configuration Instructions
  • 7.1 application.properties
  • 7.2 pom.xml
  • 8. Personal Reflection and Learnings

Contact Management System Project

Course for This Assignment2401_MU_SE_EE308
Student FZU ID832201118
Student MU lD22125345
Student NameWentao Yue
Assignment RequirementsDesign a front-end and back-end separated contact
Objectives of This AssignmentLearn software development

1. Project Overview

1.1 Overview

The Contact Management System is a front-end and back-end separated project designed to manage basic contact information, such as adding, editing, deleting, and viewing contacts. This project adopts a RESTful architecture to facilitate smooth and efficient interaction between users and the contact data, achieved through the coordinated efforts of the front end and back end.

In this system, users can manage contact information through an interactive front-end interface, where they can input details like the contact’s name, an 11-digit phone number, and an email address. The system includes data validation to ensure the accuracy of each field, with strict format checks for phone numbers, ensuring consistency and data integrity.

1.2 Technology Stack

  • Front-end: Built using HTML, CSS, and JavaScript. The front-end page offers an intuitive and visually appealing interface, with form validation and error prompts to enhance user experience. JavaScript handles API requests to the back end, enabling asynchronous data fetching and form submission for real-time page updates.

  • Back-end: Developed with the Spring Boot framework, the back end provides a reliable RESTful API. Supported by Spring Data JPA, it handles data interaction with the MySQL database. Core back-end functionalities include CRUD operations on contact data, and data validation is enforced through annotations to ensure compliance with data integrity requirements.

  • Database: MySQL is used for data storage to maintain contact information, with Hibernate ORM facilitating object-relational mapping between entity classes and database tables. JPA’s auto-configuration simplifies database operations.

  • Dependency Management: The project utilizes Maven for dependency management, incorporating libraries such as Spring Boot’s Web and JPA modules, MySQL connector, etc. Maven also integrates Spring Boot DevTools to streamline development and supports unit testing frameworks for future testing needs.



3. PSP Table

The following PSP (Personal Software Process) table details the estimated and actual time spent on each stage of development, providing a clear breakdown of the time allocated to different tasks:

PhaseEstimated Time(hours)Actual Time(hours)
Requirement Analysis12
Design34
Frontend Development33
Backend Development58
Testing58
Deployment and Presentation35
Total2030

4. Feature Demonstration

img

The following sections demonstrate each primary feature of the Contact Management System, along with animated GIFs to illustrate their functionality:

4.1 Add Contact

Users can click the "Add New Contact" button to open a form, where they input the contact’s name, 11-digit phone number, and email. After filling out the form, clicking "Save" adds the new contact to the contact list displayed on the page.

img

img

img

4.2 Edit Contact

Clicking the "Edit" button next to any contact opens an edit form, allowing users to update contact details. After making changes, users click "Save" to update the information in the list.

img

4.3 Delete Contact

The "Delete" button enables users to remove a contact from the list. Once deleted, the contact is no longer displayed in the contact list.

img

4.4 Phone Number Validation

The system validates the phone number format during the add or edit operations to ensure it consists of exactly 11 digits. If the phone number format is incorrect, an error message is displayed, and the submission is blocked until the issue is resolved.

img

img

4.5 Form Completeness Validation

The system requires all fields to be filled out before submitting contact information. If any field is left empty, an error prompt appears to prevent incomplete data from being stored in the system.

img

img


5. Design and Implementation Process

5.1 Front-End

  • Contacts.html: This HTML file serves as the main page layout, containing a table to display the contact list and an "Add New Contact" button to open the form for adding contact details (name, phone, email). The form includes "Save" and "Cancel" buttons for user interaction.

  • Contacts.css: This CSS file styles the page elements to ensure a clean and consistent layout. Button hover effects, error prompt colors, and general design choices aim to create a visually pleasing and user-friendly interface.

  • Contacts.js: The JavaScript file manages front-end functionality and handles interaction with the back end. Key functions include:

    • loadContacts(): Fetches contact data from the back-end API and displays it in the table.
    • saveContact(): Handles form submission for creating or updating a contact based on the existence of a contact-id.
    • editContact(id): Loads specific contact details into the form for editing.
    • deleteContact(id): Sends a request to delete a contact from the list.
    • Validation: Ensures that input data, particularly the phone number, conforms to the specified format.

5.2 Back-End

  • ContactController: This main controller class defines REST API endpoints and handles HTTP requests from the front end.

    • getAllContacts(): Returns a list of all contacts.
    • getContactById(Long id): Retrieves specific contact data based on its ID or returns a 404 error if not found.
    • addContact(Contact contact): Processes the addition of new contacts with validation to ensure data compliance.
    • updateContact(Long id, Contact updatedContact): Updates a contact’s details based on its ID or returns an error if not found.
    • deleteContact(Long id): Deletes a specified contact.
  • ContactService: Contains business logic, separating controller operations from the data layer. It interacts with ContactRepository to perform CRUD operations, making the code modular and easy to maintain.

  • Contact Entity: Defines the properties of a contact (id, name, phone, email) and maps these to the database table. Validation annotations such as @NotBlank, @Pattern, and @Email ensure that each field adheres to the required format.

  • ContactRepository: This repository extends JpaRepository, which provides default CRUD methods like findAll(), save(), and deleteById(), simplifying access to the database.


6. Code Analysis

6.1 ContactController: addContact Method

The addContact method in ContactController handles requests to add a new contact. It uses @Valid annotations for data validation, ensuring that the input meets the criteria defined in the Contact entity (e.g., the phone number is 11 digits, and the email is valid). If validation fails, a 400 Bad Request response is automatically generated with relevant error messages.

@PostMapping
public ResponseEntity<Contact> addContact(@Valid @RequestBody Contact contact) {
    return ResponseEntity.status(HttpStatus.CREATED).body(contactService.addContact(contact));
}

6.2 Contacts.js: saveContact Function

This function handles form submissions on the front end, determining if a contact should be added or updated.

function saveContact(event) {
    event.preventDefault();
    const id = document.getElementById('contact-id').value;
    const name = document.getElementById('name').value.trim();
    const phone = document.getElementById('phone').value.trim();
    const email = document.getElementById('email').value.trim();
    const errorMessage = document.getElementById('error-message');

    if (!name || !phone || !email) {
        errorMessage.textContent = "Please fill in all fields!";
        return;
    }

    if (phone.length !== 11 || isNaN(phone)) {
        errorMessage.textContent = "The phone number must be 11 digits!";
        return;
    }

    const contact = { name, phone, email };
    const method = id ? 'PUT' : 'POST';
    const url = id ? `${API_URL}/${id}` : API_URL;

    fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(contact)
    })
    .then(() => {
        closeForm();
        loadContacts();
    })
    .catch(error => console.error('Error saving contact:', error));
}
  • Data Validation: The function validates that all fields are filled and that the phone number is exactly 11 digits long. If validation fails, it displays an error message and prevents the form from being submitted.
  • Request Type Decision: Based on whether the contact-id is present, it determines whether to make a POST (for new contacts) or PUT (for updates) request.
  • Asynchronous Fetch Request: Sends the JSON data to the back-end API and updates the contact list upon success. If the request fails, it logs an error for debugging.

6.3 Contacts.js: loadContacts Function

The loadContacts function retrieves the list of contacts from the back end and displays it in a table format on the front end.

function loadContacts() {
    fetch(API_URL)
    .then(response => response.json())
    .then(contacts => {
        const list = document.getElementById('contacts-list');
        list.innerHTML = '';
        contacts.forEach(contact => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${contact.name}</td>
                <td>${contact.phone}</td>
                <td>${contact.email}</td>
                <td><button onclick="editContact(${contact.id})">Edit</button></td>
                <td><button onclick="deleteContact(${contact.id})">Delete</button></td>
            `;
            list.appendChild(row);
        });
    })
    .catch(error => console.error('Error loading contacts:', error));
}
  • Data Fetching: Uses fetch to make a GET request to the API and retrieve contact data.
  • Dynamic Table Update: Clears any existing rows in the table and inserts a new row for each contact, ensuring the latest data is displayed.
  • Error Handling: Logs errors to the console, aiding in troubleshooting if the data fetch fails.

6.4 Contacts.js: deleteContact Function

The deleteContact function allows users to delete a contact from the database by clicking the "Delete" button. It sends a DELETE request to the API with the contact's ID.

function deleteContact(id) {
    fetch(`${API_URL}/${id}`, { method: 'DELETE' })
    .then(() => loadContacts())
    .catch(error => console.error('Error deleting contact:', error));
}
  • Delete Request: Sends a DELETE request with the contact’s ID to remove the record from the database.
  • UI Update: Calls loadContacts upon success to refresh the list, so the user sees the changes immediately.
  • Error Handling: Logs any errors in the console if the deletion fails.

7. Configuration Instructions

7.1 application.properties

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/contacts_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
  • server.port: Specifies the port on which the application runs, set to 8080.
  • spring.datasource.url: Sets the URL for connecting to the MySQL database, including database name and timezone.
  • spring.datasource.username and password: Provide database credentials for access.
  • spring.jpa.hibernate.ddl-auto: Automatically updates the database schema for development convenience.
  • spring.jpa.show-sql: Enables SQL logging to show executed SQL statements in the console.

7.2 pom.xml

The pom.xml file manages project dependencies in a Maven-based Spring Boot project.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
</dependencies>
  • spring-boot-starter-data-jpa: Adds Spring Data JPA for database interactions.
  • spring-boot-starter-web: Provides essential components for building RESTful web services.
  • mysql-connector-j: Integrates MySQL database with the Spring Boot application.
  • spring-boot-starter-validation: Supports data validation using annotations.

8. Personal Reflection and Learnings

This project provided a comprehensive understanding of developing a full-stack application with front-end and back-end separation, enhancing my ability to handle integration effectively. Key learnings include gaining a better understanding of decoupling front-end and back-end responsibilities, implementing Cross-Origin Resource Sharing (CORS) to enable seamless communication between the two sides, and using validation annotations to ensure data integrity and robust form handling. Overall, this experience has significantly improved my skills in managing efficient and error-free data handling across systems.

...全文
31 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

167

社区成员

发帖
与我相关
我的任务
社区描述
2401_MU_SE_FZU
软件工程 高校
社区管理员
  • FZU_SE_TeacherL
  • 助教-吴可仪
  • 助教-孔志豪
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧