前后端分离实现计算器

102101632陈智鑫 2023-10-22 14:30:27
这个作业属于哪个课程2301-计算机学院-软件工程
这个作业要求在哪里第二次作业-前后端交互计算器
这个作业的目标继续实现更完善的计算器功能,体现前后端分离
其他参考文献SpringBoot、Axios

目录

  • Gitcode项目地址
  • PSP表格
  • 成品展示
  • 科学计算器
  • 功能一、基础运算
  • /功能二、清零回退
  • 功能三、错误提示
  • 功能四、读取历史记录
  • 功能五、科学计算
  • 利率计算器
  • 功能一、计算利息
  • 功能二、前端修改利息
  • 功能结构图
  • 原型设计
  • 设计实现过程
  • 代码说明
  • 前端部分代码
  • JavaScript-利率计算器
  • JavaScript-科学计算器
  • 后端部分代码
  • 利率更新
  • 心路历程和收获

Gitcode项目地址

作业代码

PSP表格

PSPPersonal Software Process Stages预估耗时(分钟)实际耗时(分钟)
Planning计划2025
• Estimate• 估计这个任务需要多少时间2025
Development开发5005850
• Analysis• 需求分析 (包括学习新技术)140130
• Design Spec• 生成设计文档3025
• Design Review• 设计复审3040
• Coding Standard• 代码规范 (为目前的开发制定合适的规范)1530
• Design• 具体设计2050
• Coding• 具体编码210260
• Code Review• 代码复审1520
• Test• 测试(自我测试,修改代码,提交修改)4030
Reporting报告170185
• Test Repor• 测试报告8085
• Size Measurement• 计算工作量4030
• Postmortem & Process Improvement Plan• 事后总结, 并提出过程改进计划5070
合计660785

成品展示

科学计算器

功能一、基础运算

计算

img


结果存储到数据库

img

/功能二、清零回退

清零

img


回退

img

功能三、错误提示

img

功能四、读取历史记录

点击ans显示历史记录,点击x取消显示

img

功能五、科学计算

三角函数计算

img


log计算、阶乘计算

img

利率计算器

功能一、计算利息

计算存款利息

img


计算贷款利息

img

功能二、前端修改利息

img

功能结构图

img

原型设计

设计实现过程

  
  function calculateInterest() {
    var rateType = document.getElementById("rate_type").value;
    var amount = document.getElementById("amount").value;
    var duration = document.getElementById("duration").value;
    
    var data = {
        rateType: rateType,
        amount: amount,
        duration: duration
    }; 
    // alert("click")
    axios.post("http://localhost:8080/t/calculateInterest", data,{
        headers:{
            "Content-Type":"application/json",
        }
    })
        .then(function(response) {
            console.log(response.data);
            //var result =response.data.interest;
            document.getElementById("result").value = response.data;
            
        })
        .catch(function(error) {
            console.error(error);
        });
}
function updateRate() {
    var rateType = document.getElementById("rate_type").value;
    var selectedOption = document.getElementById("type").value;
    var newRate = document.getElementById("newRate").value;
    
    var data = {
        rateType: rateType,
        option: selectedOption,
        rate: newRate
    };
    console.log(data)
    axios.post("http://localhost:8080/t/Rate", data, {
        headers: {
            "Content-Type": "application/json"
        }
    })
    .then(function (response) {
        //console.log(1);
        alert("修改成功");
    })
    .catch(function (error) {
        console.error(error);
    });
}

JavaScript-科学计算器

 window.onload = function () {
  const radBtn = document.getElementById('Rad');
  const degBtn = document.getElementById('Deg');

  radBtn.addEventListener('click', function () {
    radBtn.classList.add('active');
    degBtn.classList.remove('active');
  });

  degBtn.addEventListener('click', function () {
    degBtn.classList.add('active');
    radBtn.classList.remove('active');
  });

  const operationScreen = document.getElementById('operation-screen');
  const resultScreen = document.getElementById('result-screen');
  document.querySelectorAll
    ('.number, .operator, .clear, .reset, .calculate').forEach(button => {
      button.addEventListener('click', () => {
        const buttonValue = button.value;
        if (buttonValue === 'C') {
          operationScreen.textContent = '';
          resultScreen.textContent = '';
        } else if (buttonValue === '=') {
          const currentExpression = operationScreen.textContent;
          const Expression = operationScreen.textContent;
          operationScreen.textContent = currentExpression + buttonValue;
          const result = calculate(Expression);
          resultScreen.textContent = result;
          var data = {
            expression: currentExpression,
            result: result
          };
          console.log(data);
          axios.post("http://localhost:8080/t/calculate", data, {
            headers: {
              "Content-Type": "application/json",
            }
          })
            .then(function (response) {
              console.log(1);
            })
            .catch(function (error) {
              console.error(error);
            });
        }
        else if (buttonValue === 'ans') {        
            const ansButton = document.getElementById('ans');
            const calculationList = document.getElementById('history');        
            ansButton.addEventListener('click', function() {
              calculationList.style.display = 'block';
            });           
            fetch("http://localhost:8080/t/recentCalculations")
              .then(response => response.json())
              .then(data => {
                  const calculationList = document.getElementById('calculation-list');
                  calculationList.innerHTML = '';
                  data.forEach(calculation => {
                  const calculationItem = document.createElement('li');
                  calculationItem.textContent =calculation.expression +"="+ calculation.result;
                  calculationList.appendChild(calculationItem);
                  });
                });
                const delans = document.getElementById('del');
                delans.addEventListener('click',function(){
                  calculationList.style.display = 'none';
                })
        }
        else if (buttonValue === '⌫') {
          const currentExpression = operationScreen.textContent;
          operationScreen.textContent = currentExpression.slice(0, -1);
        } else {
          const currentExpression = operationScreen.textContent;
          operationScreen.textContent = currentExpression + buttonValue;
        }
      })
    })
}

后端部分代码

img

利率更新

//RateController.java
package com.example.demo3.controller;
import com.example.demo3.domain.RateRequest;
import com.example.demo3.service.RateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/t")
public class RateController {

    @Autowired
    private RateService rateService;

    @PostMapping("/Rate")

    public void UpdateRate(@RequestBody RateRequest req ) {
        String rateType = req.getRateType();
        String option = req.getOption();
        //String rateType = "deposit";
        //String option = "current";
        double rate = req.getRate();
        System.out.println(req.toString());
        String getback = rateService.UpdateRate(rateType,option,rate);
        System.out.println(getback);
        return;
    }
}
  • RateRequest 用于表示利率请求对象
//RateRequest.java
package com.example.demo3.domain;

public class RateRequest {
    private String rateType;
    private String option;
    private double rate;

    public String getRateType() {
        return rateType;
    }

    public void setRateType(String rateType) {
        this.rateType = rateType;
    }

    public String getOption() {
        return option;
    }

    public void setOption(String option) {
        this.option = option;
    }

    public double getRate() {
        return rate;
    }

    public void setRate(double rate) {
        this.rate = rate;
    }

    @Override
    public String toString() {
        return "RateRequest{" +
                "rateType='" + rateType + '\'' +
                ", option='" + option + '\'' +
                ", rate=" + rate +
                '}';
    }
}

//RateMapper.java
package com.example.demo3.mapper;


import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface RateMapper {
    void UpdateDeposit(@Param("rowType") String rowType,@Param("newRate") double newRate);
    void UpdateLoan(@Param("rowType") String rowType,@Param("newRate") double newRate);
}
// //RateMapper.xml
<?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.demo3.mapper.RateMapper">
    <update id="UpdateDeposit">
        UPDATE Deposit_interest_rate
        SET  rate = #{newRate}
        WHERE DepositTime = #{rowType}
    </update>

    <update id="UpdateLoan">
        UPDATE Loan_interest_rate
        SET rate = #{newRate}
        WHERE  LoanTime = #{rowType}
    </update>
</mapper>
  • 使用Springboot框架编写的服务类,用于处理利率修改的操作。
  • 根据rateType的值判断是更新存款利率还是贷款利率。如果是存款利率,根据selectedOption的值确定存款类型,并将新的利率传递给rateMapper.UpdateDeposit()方法进行更新。
    如果是贷款利率,根据selectedOption的值确定贷款类型,并将新的利率传递给rateMapper.UpdateLoan()方法进行更新。
// RateService.java
package com.example.demo3.service;

import com.example.demo3.mapper.RateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RateService {
    @Autowired
    private RateMapper rateMapper;
    public String UpdateRate(String rateType,String selectedOption,double newRate){
        String rowType="";
        if(rateType.equals("deposit")) {
            System.out.println(selectedOption);
            if (selectedOption.equals("current"))
                rowType = "活期";
            else if (selectedOption.equals("3months"))
                rowType = "三个月定期";
            else if (selectedOption.equals("6months"))
                rowType = "半年定期";
            else if (selectedOption.equals("1year"))
                rowType = "一年定期";
            else if (selectedOption.equals("2years"))
                rowType = "两年定期";
            else if (selectedOption.equals("3years"))
                rowType = "三年定期";
            else if(selectedOption.equals("5years"))
                rowType = "五年定期";
            System.out.println(rowType);
            System.out.println(newRate);
            rateMapper.UpdateDeposit(rowType,newRate);
        }
        else if(rateType.equals("loan")){
            if(selectedOption.equals("loan6months"))
                rowType="六个月";
            else if(selectedOption.equals("loan1year"))
                rowType="一年";
            else if(selectedOption.equals("loan1to3years"))
                rowType="一年至三年";
            else if(selectedOption.equals("loan3to5years"))
                rowType="三年至五年";
            else if(selectedOption.equals("loan5years"))
                rowType="五年";
            rateMapper.UpdateLoan(rowType,newRate);
        }
        return "ok";
    }

}

心路历程和收获

通过这次作业,我实现了前后端分离的计算器,我深刻体会到了前后端分离开发的优势,熟悉了Spring Boot和MyBatis的使用,提升了接口设计、错误处理和异常处理的能力。这是我第一次尝试前后端开发,遇到了不少问题,通过查阅文档、参考示例代码、与同学讨论等途径,不断学习和改进自己的技术能力。同时,及时反思和总结经验,以便在未来的项目中能够更好地应用所学。

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

158

社区成员

发帖
与我相关
我的任务
社区描述
FZU-CS-SE
软件工程 高校
社区管理员
  • LinQF39
  • Jcandc
  • chjinhuu
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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