福州大学第一次软件工程作业

f1232151864 2026-09-27 22:53:43

Front-End and Back-End Separation Calculator System — First Assignment

Basic Course Information

ItemContent
AssignmentFirst Assignment — Front-End and Back-End Separation Calculator System
Assignment NameFront-End and Back-End Separation Calculator System
Assignment ObjectiveBuild a calculator system based on front-end and back-end separation architecture. The front end handles user interaction and display, while the back end completes expression calculation, exception handling, and persists calculation history in MySQL. Functions include expression calculation, querying history, and deleting history records.

Table of Contents

Replace with your real GitHub links

PSP Table

PhaseEstimated Time (minutes)Actual Time (minutes)Description
Requirement Analysis60Read assignment requirements and sort out function checklist
System Overall Design80Architecture design, database table design, API interface design
Frontend Development120Page layout, input box, API invocation, rendering results and history, delete function
Backend Development180Controller, Service, expression parsing, database CRUD, exception handling
Database Design & Debugging90Create tables, configure MyBatis-Plus, debug database persistence
Frontend-Backend Joint Debugging & Testing100Connect interfaces, test various expressions and exception scenarios
Functional Testing70Test +-*/, parentheses, negative numbers, decimals, division by zero, invalid expressions, delete history
Project Deployment120Deploy backend to public server, deploy static frontend page
Blog Writing150Write blog, take screenshots, format markdown, organize code explanation
Total970

Finished Product Demonstration

  1. Main calculator interface: input box for mathematical expressions, calculate button, result display area and history record area.

img

  1. Basic addition test: inputhttps://i-blog.csdnimg.cn/communtity/3edb03f42b2e490f95d457e30e030b51.png "#left")
    12+8, backend returns result 20.

img

  1. Subtraction test: input 20-7.

img

  1. Multiplication test
    input 5*8.

img


5. Division test: input 10/2.

img

  1. Compound expression test (parentheses & operator precedence): (1+2)*3.

img

  1. Negative number expression test: -5+8.

img

  1. Decimal calculation test: 2.5+3.5.

img

  1. Exception handling: division by zero, backend returns error message.

img

  1. Invalid expression test: input 1+*3, backend returns invalid expression prompt.

img

  1. Calculation history display: load all history records from MySQL database and render on page.

img

  1. Delete history record: click delete button, backend deletes record from database, frontend refreshes history list.

img

Design and Implementation Process

1. Requirement Analysis

This project adopts front-end and back-end separation architecture:

  • Frontend: Responsible only for UI interaction. Receive user input expressions, send HTTP requests to backend, display results and error messages. Query and delete history records. No mathematical calculation is performed on the frontend.
  • Backend: Receive expression string, validate expression syntax, parse and compute mathematical expression. Catch exceptions such as division by zero and syntax error. Save successful calculation records into MySQL. Provide APIs to query all history and delete record by id.
  • Database: Persist calculation records. Data will not be lost after backend service restarts.

2. System Architecture

Frontend Web Page (HTML+JS)
↓ HTTP JSON Request
Backend SpringBoot Service
↓ MyBatis-Plus
MySQL Database (calculation_history table)
Calculator System
├── Calculation Module
│ ├── Basic Four Arithmetic Operations
│ ├── Compound Expression Calculation (Parentheses, Negative Numbers, Decimals, Operator Precedence)
│ └── Exception Handling (Division by Zero, Invalid Expression)
└── History Record Module
├── Save Calculation Record
├── Query All History
└── Delete Single History Record

3. API Design

  1. POST /api/calculate
    Request body: {"expression":"(1+2)*3"}
    Success response: {"success":true,"expression":"(1+2)*3","result":9}
    Failure response: {"success":false,"message":"error description"}

  2. GET /api/history
    Return full list of history records stored in database.

  3. DELETE /api/history/{id}
    Delete one record from database by primary key id.

4. Database Design

Database name: calculator_db
Table name: calculation_history

FieldTypeDescription
idBIGINT auto-increment primary keyUnique ID of record
expressionVARCHAR(512)Mathematical expression input by user
resultDECIMAL(20,6)Calculation result
created_atDATETIMECalculation time, default current timestamp

5. Module Design

  1. Controller Layer: Receive HTTP requests, read parameters, call service layer and wrap response data.
  2. Service Layer: Expression validation, expression calculation logic, database read/write, exception capture.
  3. Mapper Layer: Use MyBatis-Plus to operate MySQL database.
  4. Frontend Module: Read user input, fetch network request, render page, handle delete interaction.

6. Exception Handling

Backend captures multiple types of exceptions:

  • Syntax error, mismatched parentheses
  • Division by zero
  • Empty input or invalid characters
    When exceptions are caught, return success:false plus human-readable error message to frontend for display.

7. Deployment Process

  1. Package SpringBoot backend into jar file, deploy to cloud server and open port 8080 for public access.
  2. Deploy static HTML frontend page to Github Pages.
  3. Test public network access and verify all functions.

Code Explanation

Only paste core code snippets, add explanations, do NOT paste full source code.

1. Frontend core: call backend calculation API

async function calc() {
  const expr = document.getElementById("exprInput").value;
  const res = await fetch(baseUrl + "/calculate", {
    method: "POST",
    headers: {"Content-Type":"application/json"},
    body: JSON.stringify({expression: expr})
  });
  const data = await res.json();
  if(data.success){
    resultDiv.innerText = `✅Expression: ${data.expression}, Result: ${data.result}`;
  }else{
    resultDiv.innerText = `❌Error: ${data.message}`;
  }
  await loadHistory();
}
Explanation: Frontend reads user input expression, sends POST JSON request to backend. Frontend does NOT perform calculation. After receiving response, render result and reload history list.
2. Backend Controller example
@PostMapping("/calculate")
public Result calculate(@RequestBody ExpressionDTO dto){
    return calcService.calculate(dto.getExpression());
}
Explanation: Receive POST request and expression string, pass expression to service layer for processing.
3. Backend Service: calculate and save to database
// 1. parse and calculate expression
BigDecimal result = expressionUtil.calc(expression);
// 2. insert record into MySQL
CalculationHistory history = new CalculationHistory();
history.setExpression(expression);
history.setResult(result);
historyMapper.insert(history);
// return result
return Result.success(expression, result);
Explanation: Backend executes expression calculation. If successful, create new record and insert into MySQL. Data is persisted and survives service restart.
4. Query history API
@GetMapping("/history")
public List<CalculationHistory> getHistory(){
    return historyMapper.selectList(null);
}
5. Delete history API
@DeleteMapping("/history/{id}")
public Result deleteHistory(@PathVariable Long id){
    historyMapper.deleteById(id);
    return Result.successMsg("Delete success");
}
6. Database entity class (simplified)
@Data
@TableName("calculation_history")
public class CalculationHistory {
    private Long id;
    private String expression;
    private BigDecimal result;
    private LocalDateTime createdAt;
}
...全文
56 回复 打赏 收藏 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

91

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯-软件工程
软件工程 高校 福建省·福州市
社区管理员
  • FZU_SE_LQF
  • zjcTander
  • 木村修
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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