java-SpringBoot框架开发计算器网页端编程练习项目【web版】

72 阅读1分钟

今天分享一个使用springboot 写一个 前后端不分离的项目,网页计算器,来熟悉springboot框架的使用。

java版本:8

springboot:2.6.13

使用的技术是:

Java + Spring Boot + Thymeleaf + HTML/CSS/JS 构建的 Web 端简约按钮式计算器。

熟悉 Spring Boot 控制器(@Controller, @GetMapping, @PostMapping)

· 掌握表单提交与参数绑定(@RequestParam)

· 学会使用 Thymeleaf 在前端绑定变量

· 理解 HTML 与 JS 如何联动后端数据

先给大家看一下做出来的效果:

image.png

项目部分代码:

package com.jsonl.jisuanqi.controller;

/***
 * User: Json
 * Date: 2025/6/21
 **/

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * User:Json
 * Date: 2025/6/21
 **/
@Controller
public class IndexController {
    // 创建 JavaScript 脚本引擎,用于后端计算表达式
    private final ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

    // 显示主页面,初始化表达式为空
    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("expression", ""); // 页面首次加载无表达式
        return "calculator"; // 返回 calculator.html
    }

    // 处理计算按钮提交的表达式
    @PostMapping("/calculate")
    public String calculate(@RequestParam String expression, Model model) {
        try {
            // 若表达式为空或无效,设置错误信息
            if (expression == null || expression.trim().isEmpty()) {
                model.addAttribute("result", "错误");
                expression = "";
            } else {
                // 使用 JavaScript 引擎计算表达式结果
                Object result = engine.eval(expression);
                model.addAttribute("result", result.toString()); // 设置结果
                expression = result.toString(); // 把结果变成新表达式,支持连续计算
            }
        } catch (Exception e) {
            // 计算出错时显示“错误”
            model.addAttribute("result", "错误");
            expression = "";
        }

        // 将最新表达式返回页面继续显示
        model.addAttribute("expression", expression);
        return "calculator";
    }

    // 清除表达式(点击 C 时)
    @GetMapping("/reset")
    public String reset(Model model) {
        model.addAttribute("expression", "");
        model.addAttribute("result", "");
        return "calculator";
    }
}

image.png

有兴趣的小伙伴,可以拿去看看,希望能在你编程学习的过程中帮助到你。

完整代码和简单的操作说明已经打包好了。可以获取:

wwwoop.com/home/Index/…