软件园学生在线

  • {{ item.name }}
  • 2023试用期

登录与注册

【后端一】 王春雨

  • 王春雨
  • 2022-10-15
  • 0

(这是一篇充满了努力过却依旧找不到解决方法的问题的文章,求大佬答疑/(ㄒoㄒ)/~~)

目录:
一、基本的四则运算
拓展一、实数的四则运算
拓展二、判断数据是否溢出、输入错误信息报错
拓展三、做个简单的前端
二、其他 (一)修改端口号

(没错 没了)

一、基本的四则运算

首先,按照课上所讲的方法,成功的创建一个Spring boot项目

并按照加法的操作方法,很简单的延展为支持四则运算的API

代码如下:

package com.example.firstspringboot.comtroller;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
public class Main {

    @GetMapping("/plus")
    public int plus(@RequestParam int a,@RequestParam int b){
        return a+b;
    }

    @GetMapping("/minus")
    public int minus(@RequestParam int a,@RequestParam int b){
        return a-b;
    }

    @GetMapping("/multiply")
    public int multiply(@RequestParam int a,@RequestParam int b){
        return a*b;
    }

    @GetMapping("/divide")
    public int divide(@RequestParam int a,@RequestParam int b){
        return a/b;
    }
}

在运行后,我们在浏览器打开
localhost:8080/plus?a=100&b=150
即可成功得到结果

同理:
localhost:8080/minus?a=100&b=50
localhost:8080/multiply?a=100&b=50
localhost:8080/divide?a=100&b=50

均可以得到类似的结果。


但,问题来了,如果在计算除法时结果不是整数该怎么办呢?

如果计算机把结果强制转换为整数,会损失精度,例如:

当我在浏览器打开localhost:8080/divide?a=50&b=100 时
得到的结果为

这显然与我们想获得差距过大,因此我们需要进行拓展

拓展一、实数的四则运算

从整数到实数的转变很简单,只需把所有定义的int型变量改为double型变量即可,于是,我们得到了以下代码:

package com.example.firstspringboot.comtroller;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
public class Main {

    @GetMapping("/plus")
    public double plus(@RequestParam double a,@RequestParam double b){
        return a+b;
    }

    @GetMapping("/minus")
    public double minus(@RequestParam double a,@RequestParam double b){
        return a-b;
    }

    @GetMapping("/multiply")
    public double multiply(@RequestParam double a,@RequestParam double b){
        return a*b;
    }

    @GetMapping("/divide")
    public double divide(@RequestParam double a,@RequestParam double b){
        return a/b;
    }
}

到这里,就升级成功啦!

不知为何,从这里往下就与上课教的没有任何关联了!!!!


经过查询可知:
double的范围为-2^1024 ~ +2^1024,也即-1.79E+308 ~ +1.79E+308
java中int范围是-2147483648到2147483647
每一个基本数据类型都是有范围的,所以我们需要考虑数据溢出的可能。

拓展二、判断数据是否溢出、输入错误信息报错

(由于double范围较大,此处我们使用int为例)

当我在浏览器打开localhost:8080/multiply?a=2147483645&b=10 后,得到了如下结果:

这显然是结果超出int范围所导致而出现的错误结果,我们希望他能够在溢出时提示错误

(这里还不会,先跳了)


若计算四则运算,用户输入的数据应该为实数,但若输入的非实数,则会得到以下结果:

可通过这个我们并无法判断是为何出现这个页面(?),我们希望他能够明确提示我们:您输入的为非法数据!

(这里也还不会,婉跳了昂)


拓展三、做个简单的前端

为了做一个“简单的前端”我成功混入他们的培训群(这里十分惊讶于我清晰的在申请中表明了后端卧底的身份还是秒过认证)去蹭了前端的课,学会了写简单的前端/gz
刚写完的时候效果如下:

但如何才能将前端输入的数据传到后端,前端没教啊/dk
如何才能把后端计算后得到的数据在前端展示,后端没教啊/dk
证明我曾努力过,这是我尝试了网络上说的但依旧没有做到成功与后端传递数据的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Calculate</title>
</head>
<h2 style="text-align: center">Calculate</h2>
<br>

<body style="background-color: lightsteelblue">
<div style="text-align: center">
<form name="user" action="@{/calculate}" method="post">
    num1:<input type="number" name="a" max="2147483647" min="-2147483648">
    <select name="type" onchange="show(this.options[this.options.selectedIndex].value)">
        <option value="plus">+</option>
        <option value="minus">-</option>
        <option value="multiply">*</option>
        <option value="divide">/</option>
    </select>
    num2:<input type="number" name="b" max="2147483647" min="-2147483648">
    </form>
    </div>
<form>
    <br><div style="text-align: center">
    <button class="btn">=</button>
    </div>
</form>

</body>
</html>

效果↓

【达成成就】前是前 后是后 前不是后 后不是前
暂且学不会了......再婉跳了吧......

这里分享一个趣事

关于复制前端的代码在电脑端qq发出后的效果

神奇的表情 /bu /ht /se

二、其他

(一)修改端口号
法一:Properties

server.port=1129

即可将端口修改为1129

法二:Yml
server:
  port: 1129
  ```

这两种方法差距并不是很大,但yml代码更显层次感,需要注意的是,在yml代码中冒号“:”后需要加一个空格在写值

(虽然跳了很多,但真的尽力了呜呜呜呜呜,总监能不能教的全一些呜呜呜,做不到拓展难受啊啊啊啊啊啊)
(先提交了吧,我还在努力,学会了就回来把不会的都改了)

# 更新

```java
package com.example.first_homework.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/calculator")
public class CalculatorController {

    @GetMapping("/add")
    public String add(@RequestParam("a") String a, @RequestParam("b") String b) {
        // 校验参数是否为空
        if (StringUtils.isEmpty(a) || StringUtils.isEmpty(b)) {
            throw new IllegalArgumentException("Parameters cannot be empty");
        }

        // 将字符串参数转换为数字
        double operand1 = parseDouble(a);
        double operand2 = parseDouble(b);

        // 执行加法运算
        double result = operand1 + operand2;

        // 返回结果
        return String.valueOf(result);
    }

    @GetMapping("/subtract")
    public String subtract(@RequestParam("a") String a, @RequestParam("b") String b) {
        // 校验参数是否为空
        if (StringUtils.isEmpty(a) || StringUtils.isEmpty(b)) {
            throw new IllegalArgumentException("Parameters cannot be empty");
        }

        // 将字符串参数转换为数字
        double operand1 = parseDouble(a);
        double operand2 = parseDouble(b);

        // 执行减法运算
        double result = operand1 - operand2;

        // 返回结果
        return String.valueOf(result);
    }

    @GetMapping("/multiply")
    public String multiply(@RequestParam("a") String a, @RequestParam("b") String b) {
        // 校验参数是否为空
        if (StringUtils.isEmpty(a) || StringUtils.isEmpty(b)) {
            throw new IllegalArgumentException("Parameters cannot be empty");
        }

        // 将字符串参数转换为数字
        double operand1 = parseDouble(a);
        double operand2 = parseDouble(b);

        // 执行乘法运算
        double result = operand1 * operand2;

        // 返回结果
        return String.valueOf(result);
    }

    @GetMapping("/divide")
    public String divide(@RequestParam("a") String a, @RequestParam("b") String b) {
        // 校验参数是否为空
        if (StringUtils.isEmpty(a) || StringUtils.isEmpty(b)) {
            throw new IllegalArgumentException("Parameters cannot be empty");
        }

        // 将字符串参数转换为数字
        double operand1 = parseDouble(a);
        double operand2 = parseDouble(b);

        // 校验除数是否为零
        if (operand2 == 0) {
            throw new IllegalArgumentException("Divisor cannot be zero");
        }

        // 执行除法运算
        double result = operand1 / operand2;

        // 返回结果
        return String.valueOf(result);
    }

    // 辅助方法:将字符串转换为 double 类型,处理小数运算和数据溢出的问题
    private double parseDouble(String value) {
        try {
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid parameter: " + value);
        }
    }
}
<!DOCTYPE html>
    <html>
    <head>
        <title>Calculator</title>
        <style>
            .container {
                text-align: center;
            }

            .input-group {
                margin-bottom: 10px;
            }

            .result {
                font-weight: bold;
            }
        </style>
    </head>
    <body>
    <div class="container">
        <h1>Calculator</h1>
        <div class="input-group">
            <label for="operand1">Operand 1:</label>
            <input type="text" id="operand1">
        </div>
        <div class="input-group">
            <label for="operand2">Operand 2:</label>
            <input type="text" id="operand2">
        </div>
        <button onclick="calculate()">Calculate</button>
        <div class="result">
            Result: <span id="result"></span>
        </div>
    </div>

    <script>
        function calculate() {
            // 获取输入框的值
            var operand1 = document.getElementById("operand1").value;
            var operand2 = document.getElementById("operand2").value;

            // 发起 API 请求
            fetch("http://localhost:8080/api/calculator/add?a=" + operand1 + "&b=" + operand2)
                .then(response => response.text())
                .then(result => {
                    // 显示计算结果
                    document.getElementById("result").textContent = result;
                })
                .catch(error => {
                    // 处理错误情况
                    document.getElementById("result").textContent = "Error: " + error.message;
                });
        }
    </script>
    </body>
    </html>
package com.example.first_homework;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
public class FirstHomeworkApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstHomeworkApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*");
            }
        };
    }
}
王春雨
王春雨
© 2025 软件园学生在线
Theme by Wing