Separate front and rear end calculator

目录

I   Project Introduction

I.I Information table

I.II PSP Table

II problem-solving ideas

1.Testing and validation

2.User feedback and iteration

3.Deployment and hosting

4.Performance optimization

III The process of design and implementation

1.Requirement gathering

2.Conceptual design

3.Wireframing

4.User interface (UI) design

5.Front-end development

6.Back-end development

7.Integration

8.Testing and debugging

9.Deployment and launch

10.Maintenance and updates

IV Coding

IV.I Front_end coding

HTML

CSS

JavaScript 

IV.I Back_end coding

Mapper XML

Interface setup

V Result Displaying

VI Summary


I   Project Introduction

        The Simple Calculator is a web application developed using HTML, CSS, and JavaScript for the front-end, and Spring Boot with MyBatis for the back-end. The project aims to provide a user-friendly interface that allows users to perform basic mathematical calculations.

GitHub - SORRYMAKER2033/Back-end-separation-calculator: The Simple Calculator is a web application developed using HTML, CSS, and JavaScript for the front-end, and Spring Boot with MyBatis for the back-end.

I.I Information table

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617378696
The Aim of This AssignmentCreate a back-end separation calculator with a visual interface.
MU STU ID and FZU STU ID21126291______832101114

I.II PSP Table

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning 3060
• Estimate3060
Development11801500
• Analysis120180
• Design Spec90120
• Design Review3040
• Coding Standard4060
• Design6060
• Coding600840
• Code Review60100
• Test180100
Reporting190120
• Test Report12060
• Size Measurement2030
• Postmortem & Process Improvement Plan5030
Sum 14001680

II problem-solving ideas

1.Testing and validation

        Once the calculator implementation is complete, it's important to thoroughly test the application to ensure it functions correctly and provides accurate results. Test different scenarios, edge cases, and user inputs to validate the calculator's behavior. Fix any bugs or issues identified during the testing process.

2.User feedback and iteration

        Gather feedback from users or potential users of the calculator. This can be done through user testing, surveys, or feedback forms. Analyze the feedback received and identify areas for improvement or additional features that users may find valuable. Iterate on the calculator based on user feedback to enhance its usability and functionality.

3.Deployment and hosting

        Prepare the calculator for deployment by packaging the front-end code and setting up the back-end server. Choose a suitable hosting platform or server to deploy the application, ensuring it is accessible to users. Configure the necessary infrastructure, such as domain setup or cloud hosting, to host the calculator reliably.

4.Performance optimization

        Analyze the performance of the calculator and identify areas where optimization can be applied. This includes optimizing the code, reducing response times, and handling large-scale calculations efficiently. Implement caching mechanisms, compress and minify assets, and make use of performance monitoring tools to optimize the calculator's performance.

III The process of design and implementation

1.Requirement gathering

        Begin by understanding the requirements and goals of the web calculator project. This involves gathering information about the desired features, target audience, user expectations, and any specific design or functionality requests.

2.Conceptual design

        Create a high-level conceptual design for the web calculator. This includes defining the overall layout, user interface components, and the flow of user interactions. Consider the aesthetic aspects, usability, and intuitive navigation during this stage.

3.Wireframing

        Develop wireframes or low-fidelity prototypes to visualize the structure and layout of the web calculator. Use wireframing tools or simply sketch out the design on paper to establish the placement of different elements such as buttons, input fields, and result displays.

4.User interface (UI) design

        Translate the wireframes into a visually appealing and user-friendly interface. Design the UI elements, typography, color scheme, and overall style to create a cohesive and engaging user experience. Use design tools or libraries to create mockups or prototypes with more detailed visual representations.

5.Front-end development

        Begin implementing the UI and functionality using HTML, CSS, and JavaScript. Write the HTML markup to structure the calculator's components, apply CSS styles for visual presentation, and implement interactive behavior using JavaScript. Ensure the design is responsive, adapting to different device sizes and orientations.

6.Back-end development

        Set up the back-end infrastructure required for the calculator. This includes building server-side logic and handling incoming requests from the front-end. Use frameworks like Spring Boot and libraries like MyBatis to handle API interactions, perform calculations, and store any necessary data.

7.Integration

        Connect the front-end and back-end components to establish communication between the user interface and the server-side functionality. Pass user input from the front-end to the back-end for processing, and receive and display the calculated results or error messages from the back-end on the front-end interface.

8.Testing and debugging

        Conduct comprehensive testing to ensure the web calculator functions as expected and provides accurate results. Test different scenarios, edge cases, and user inputs to verify the correctness of calculations and identify and fix any bugs or issues encountered.

9.Deployment and launch

        Prepare the web calculator for deployment on a hosting platform or server. Configure the necessary infrastructure, such as domain setup, hosting environment, and security measures. Perform final testing in the production environment and launch the web calculator for public use.

10.Maintenance and updates

        Regularly monitor the web calculator for performance, security, and usability. Address any reported issues or user feedback promptly. Implement updates and improvements based on user needs, technological advancements, and changing requirements to ensure the calculator remains functional and up to date.

IV Coding

IV.I Front_end coding

HTML

        HTML is mainly used to implement the structure of the computer interface. I created a div that contains all the buttons and screen elements of the calculator. I've divided them into three main button blocks: the regular compute button, the control keys (the "C" and "DEL" keys), and the advanced compute button, with each button block containing a corresponding element. In addition, I created an input field element as a display screen to display the calculation process and results.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计算器</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="calculator">
        <input type="text" id="display" disabled>
        <div id="control-keys">
            <button>C</button>
            <button>DEL</button>
            <button>Ans</button>
            <button>history</button>
        </div>
        <div id="buttons">
            <button>1</button>
            <button>2</button>
            <button>3</button>
            <button>/</button>
            <button>4</button>
            <button>5</button>
            <button>6</button>
            <button>*</button>
            <button>7</button>
            <button>8</button>
            <button>9</button>
            <button>-</button>
            <button>.</button>
            <button>0</button>
            <button>=</button>
            <button>+</button>
            <button>(</button>
            <button>)</button>
            <button>%</button>
            
        </div>
        <div id="advanced-buttons">
            <button>e^x</button>
            <button>e</button>
            <button>π</button>
            <button>ln</button>
            <button>log</button>
            <button>x^y</button>
            <button>√</button>
            <button>sin</button>
            <button>cos</button>
            <button>tan</button>

        </div>
    </div>
    <div id="history"></div> <!-- 添加历史记录显示区域 -->
    <div id="last-record"></div><!-- 添加最后一次的历史记录显示区域 -->
    <script src="calculator.js"></script>
</body>
</html>

CSS

        This page design I have added two new display areas, one used to display history, one used to display the latest calculation record.The new code is as follows:

#history {
  height: 100px;
  margin-top: 20px;
  padding: 10px;
  overflow: auto;
  background-color: #404040; /* 修改历史记录区域的背景颜色 */
  color: #fff;
}

#last-record {
  height: 50px;
  margin-top: 20px;
  padding: 10px;
  background-color: #404040;
  color: #fff;
}

JavaScript 

        In this js design, I designed that when the user clicks the three keys "Ans", "=" and "history", three functions will be referenced respectively:

function showLastCalculations() {
  lastRecordEl.innerHTML = '';
  fetch("http://localhost:8080/calculate/getLastRecord", {
    method: 'POST'
  })
    .then(response => {
      if (response.ok) {
        response.json().then(records => {
          console.log(records); // 调试语句
          const lastRecordEl = document.getElementById('last-record');
          lastRecordEl.innerHTML = ''; // 清空容器元素

          records.forEach(record => {
            let pEl = document.createElement('div');
            pEl.innerText = record.formula + ' = ' + record.result;
            lastRecordEl.append(pEl);
          });
        });
      } else {
        throw new Error('无法获取最后一次计算过程');
      }
    })
    .catch(error => {
      alert(error.message);
    });
}
function saveHistory(formula, result) {
  fetch("http://localhost:8080/calculate/save", {
    method: 'POST',
    body: JSON.stringify({ formula: formula, result: result }),
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => {
    response.text().then(data => {
      console.log(data);
      getHistory(page);
    })
  }).catch(error => {
    alert('网络错误')
  })
}
function getHistory() {
  fetch("http://localhost:8080/calculate/queryAllByPage?page=" + page, {
    method: 'POST'
  }).then(response => {
    response.json().then(data => {
      console.log(data);
      historyEl.innerHTML = ''
      data.forEach(item => {
        let pEl = document.createElement('p')
        pEl.innerText = item.formula + ' = ' + item.result
        historyEl.append(pEl)
      })
    })
  }).catch(error => {
    alert('网络错误')
  })
}

        These three functions I set three interfaces in the back-end code so that I can call them in js (the functions are to display the latest calculation record, store record, and display nearly ten records, respectively).

        In the process of testing the code, I found that the calculator could not store the calculation process (only the result) in the advanced calculation, because the user clicked on the calculator to display the result directly when the user clicked on the trigonometric function calculation, for example, the calculator did not click the "=" key process, so I adjusted the click event of the advanced calculation button in js (only let them show the process. The result is only displayed after clicking "=") The code is as follows

// 高级运算按钮点击事件
document.getElementById("advanced-buttons").addEventListener("click", function (e) {
  if (e.target.matches("button")) {
    var op = e.target.innerText;
    var curVal = parseFloat(display.value);
    switch (op) {
      case 'e^x':
        display.value = `Math.exp(${curVal})`; // 显示计算过程
        break;
      case 'e':
        display.value = Math.E.toString();
        break;
      case 'ln':
        display.value = `Math.log(${curVal})`; // 显示计算过程
        break;
      case 'x^y':
        display.value = `Math.pow(${curVal}, y)`; // 这里假设y是想要使用的变量
        break;
      case '√':
        display.value = `Math.sqrt(${curVal})`; // 显示计算过程
        break;
      case 'sin':
        var rad = curVal * (Math.PI / 180); // 把角度转换为弧度
        display.value = `Math.sin(${curVal})`; // 显示计算过程
        break;
      case 'cos':
        var rad = curVal * (Math.PI / 180); // 把角度转换为弧度
        display.value = `Math.cos(${curVal})`; // 显示计算过程
        break;
      case 'tan':
        var rad = curVal * (Math.PI / 180); // 把角度转换为弧度
        display.value = `Math.tan(${curVal})`; // 显示计算过程
        break;
      case 'log':
        display.value = `Math.log10(${curVal})`; // 显示计算过程
        break;
      case 'π':
      display.value = Math.PI.toString();
      break;
    }
  }
});

IV.I Back_end coding

Mapper XML

        Configure mapping relationships for database tables and various SQL statements

        The second line is a declaration of the Document Type Definition (DTD), which validates the structure of the XML document.< mapper > tag specifies the namespace (namespace) for the com. Example. Calculator. Dao. CalculateDao, representing the XML file corresponding to the CalculateDao interface.The <resultMap> tag defines the identifier of a resultMap as BaseResultMap, and specifies the mapping relationship between the attributes of the Calculate entity class and database tables.The select tag defines four query statements that query a single record by ID, query all records, paginate all records, and get the last record.
The insert tag defines the statement to add the record.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.calculator.dao.CalculateDao">

    <resultMap id="BaseResultMap" type="com.example.calculator.entity.Calculate">
        <!--@Table admin-->
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="formula" column="formula" jdbcType="VARCHAR"/>
        <result property="result" column="result" jdbcType="VARCHAR"/>
    </resultMap>

Interface setup

        This code is an example of an interface setup that defines and describes a function point or service in the system. In this case, we have an interface called CalculateService, which defines a set of operations to handle computing-related functions.

    @PostMapping("getLastRecord")
    public List<Calculate> getLastRecord() {
        return (List<Calculate>) this.calculateService.getLastRecord();
    }

    /**
     * 分页查询所有数据
     *
     */
    @PostMapping("queryAllByPage")
    public List<Calculate> queryAll(Integer page) {
        List<Calculate> calculateList = this.calculateService.queryAllByPage(page);
        return calculateList;
    }

    /**
     * 新增数据
     *
     * @param calculate 实例对象
     * @return 实例对象
     */
    @PostMapping("save")
    public String insert(@RequestBody Calculate calculate) {
        this.calculateService.insert(calculate);
        return "ok";
    }
   @Override
    public void insert(Calculate calculate) {
        this.calculateDao.insert(calculate);
    }

    @Override
    public List<Calculate> queryAllByPage(Integer page) {
        return calculateDao.queryAllByPage(page);
    }

    @Override
    public List<Calculate> getLastRecord() {
        return calculateDao.getLastRecord();
    }
    void insert(Calculate calculate);

    /**
     * 分页查询所有数据
     *
     * @param page 页码
     * @return 对象列表
     */
    List<Calculate> queryAllByPage(Integer page);

    /**
     * 获取数据库中最后一条数据
     *
     * @return 最后一条记录的实例对象
     */
    List<Calculate> getLastRecord();

I wrote this code with the following questions in mind:

Functional requirements: First, I need to clearly identify what computing capabilities we need to provide. For example, you can query a single piece of data, query all data, and add data. These requirements will serve as the definition of the interface method.

Method definition: Based on the functional requirements, I defined the corresponding interface method for each required computing function. For example, queryById() is used to query a single piece of data by ID, queryAll() is used to query all data, insert() is used to add new data, and so on.

Parameters and return values: Next, I consider the parameters and return values of each method. For example, the queryById() method takes an integer ID as an argument and returns the corresponding instance object.

Database operations: When implementing the concrete methods of the interface, I need to use the database access layer (for example, CalculateDao) to perform the corresponding database operations. This database access layer can be retrieved by injection (using @Resource or other dependency injection) and then the corresponding method is called.

Using Spring Boot to set up the backend:

For the back end, I used the popular Java framework Spring Boot to handle HTTP requests and act as a bridge between the front end and the database. I configured the project structure, application properties, and defined the necessary dependencies.

Integration with MyBatis for data persistence:

I integrated MyBatis, a Java-based persistence framework for interacting with the database and performing CRUD operations. I created entity classes to represent the calculator's data, and wrote the MyBatis mapper interface and XML files to perform queries and manage data persistence.

Create an API endpoint:

With Spring Boot, I defined a RESTful API endpoint to handle requests from the front end. I implemented controller classes and mapped them to specific urls to enable the front end to communicate with the back end and do things like compute, retrieve records, or save data.

V Result Displaying

        The following GIFs and pictures show the "Ans" project to display the latest calculation record, residual calculation, trigonometric calculation, logarithm calculation, and all the historical records stored and displayed.

VI Summary

        During the development of a calculator project, I gained valuable experience and learned important lessons in creating a frontend-backend separated application using HTML, CSS, JavaScript for the frontend, and Spring Boot with MyBatis for the backend.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值