基于SpringBoot的加法计算器

文章目录


前言

需求:输入两个整数,点击"点击相加"按钮,显示计算结果


一、准备工作

1、创建SpringBoot项目:

引入SpringWeb依赖,把前端页面放在项目里

2、前端代码如下:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     <form action="calc/sum" method="post">
        <h1>计算器</h1>
        数字1:<input name="num1" type="text"><br>
        数字2:<input name="num2" type="text"><br>
        <input type="submit" value=" 点击相加 ">
    </form>
</body>
</html>

二、项目的设计

1.需求分析

加法计算器的功能,对两个整数进行相加,需要客户端提供参与计算的两个数,服务端返回这两个整数的计算结果

2.接口定义

c 复制代码
1 请求路径:calc/sum
2 请求方式:GET/POST
3 接口描述:计算两个整数相加

3.请求参数

参数名 类型 是否必须 备注
num1 Integer 是 参与计算的第一个数
num2 Integer 是 参与计算的第二个数

4.响应数据

c 复制代码
Content-Type:test/html
响应内容:计算机的结果:8

5.服务器代码

java 复制代码
package org.example.testdemo;

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

@RequestMapping("/calc")
@RestController
public class CalcController {
    @RequestMapping("/sum")
    public String sum(Integer num1, Integer num2) {
        if (num1 == null || num2 == null) {
            return "输入不合法";
        }
        Integer sum = num1 + num2;
        return "计算机计算结果: " + sum;
    }

}

三、项目运行

运行结果如下图:



总结

该项目完整演示了前后端交互的基本流程,涵盖了参数传递、业务处理、结果返回等关键环节,是理解Web开发基础的良好案例。通过此项目可以掌握SpringBoot控制器编写、请求映射配置等核心技能。各位大佬一键三连!

相关推荐
lizhongxuan1 分钟前
让 AI 提效转化为团队交付
后端
颜进强19 分钟前
23 · NestJs ModuleRef 模块引用:容器递给你的"取货窗口",四个 API 四种语义
前端·后端·ai编程
captain37621 分钟前
Maven
java·后端·idea
hsfxuebao22 分钟前
Loop Engineering 已死? 一文带你了解Graph Engineering
人工智能·后端
萧瑟余晖30 分钟前
Spring Boot Web开发与内嵌容器详解
spring boot
liangshanbo121544 分钟前
主系统登录后,子系统怎么实现自动登录?
java·网络·数据库
颜进强1 小时前
22 · NestJs InjectionScopes 注入作用域:默认单例不是偷懒,是最优——以及何时才该打破
前端·后端·ai编程
ShineWinsu1 小时前
对于Redis:缓存的解析
java·redis·缓存·缓存穿透·缓存击穿·缓存雪崩·缓存预热
rannn_1111 小时前
【Java面试题】高频面试题1|Java 后端、MySQL、Redis 与 RAG 面试整理
java·jvm·数据库·后端·面试
写后端的胖头鱼1 小时前
一文详解Spring 事务失效场景
java·spring·事务·transactional·事务传播机制