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.

...全文
159 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
代码下载地址: https://pan.quark.cn/s/a4b39357ea24 ### HSMS/SEMI通讯E37说明书中文关键知识点 #### 一、HSMS概述 - **HSMS**(High-Speed SECS Message Service)是一种专为半导体工厂内部计算机之间进行高速消息传输而构建的通信标准。该标准旨在逐步取代原有的SEMIE4(SECS-I)和SEMIE13(SECS Message Service),特别是在需要高速数据交换或简单的点对点拓扑结构无法满足实际需求的情况下。 - HSMS的核心宗旨在于提供一种机制,使来自不同制造商的设备能够达成无缝对接和互操作状态,即便这些设备在设计理念和通信机制上存在显著差异。 - HSMS不仅适用于TCP/IP优先于OSI模型的应用环境,同时也能作为SEMIE4和SEMIE13的有效替代方案。 #### 二、HSMS的应用范围 - HSMS主要部署于半导体制造业中的计算机系统之间进行消息交换的场景,如自动化生产线、设备监控系统等。 - 该标准界定了通信接口,使得半导体工厂内的各类设备能够实现高效且可靠的数据传输。 #### 三、HSMS与其他标准的关系 - **SEMIE4 (SECS-I)**:规定了消息传输的基本规则和格式。 - **SEMIE5 (SECS-II)**:明确了消息的具体内容和结构。 - **IETF Documents**: - RFC791 - Internet协议 - RFC792 - Internet控制消息协议 - RFC793 - 传输控制协议 - RFC1120 - Internet主机通信层的要求 - RFC1340 - 指定号码 - **POSIX D...
内容概要:本文系统研究了虚拟同步发电机(VSG)的惯量-阻尼协同自适应并网控制策略,旨在提升微电网在并网过程中的频率稳定性与动态响应能力。通过Simulink搭建VSG控制模型,结合Matlab实现算法仿真,深入分析了惯量与阻尼参数的自适应调节机制,并融合黑启动、预同步控制、虚拟阻抗等关键技术,有效增强了系统在电网频率波动下的鲁棒性与功率分配均衡性。研究不仅构建了完整的VSG双机并联仿真平台,还验证了所提控制策略在微电网黑启动、并网切换及负载突变等典型工况下的可行性与优越性,为新能源并网系统的稳定性控制提供了理论依据与技术支撑。; 适合人群:具备电力系统、自动化、电气工程等相关专业背景,熟悉Matlab/Simulink仿真环境,从事新能源并网、微电网控制、虚拟同步机技术、电力电子与电力系统稳定性研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①掌握虚拟同步发电机的核心控制原理及其在微电网中的应用;②学习惯量与阻尼参数的协同自适应调控方法,提升系统频率响应性能;③通过Simulink搭建双机并联VSG系统,完成黑启动、预同步、功率均分等关键过程的仿真验证;④为科研论文复现、课题设计或实际工程项目提供可复用的模型与算法参考。; 阅读建议:建议读者结合文中所述仿真模型与代码资源,按照控制策略的设计流程逐步实践,重点关注参数整定、控制环路设计及系统稳定性判据的分析。推荐关注公众号“荔枝科研社”获取完整资料包,以便深入理解并拓展至更复杂的多源协同控制场景。

173

社区成员

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

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