今天分享一個使用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 如何聯動后端數據
先給大家看一下做出來的效果:
項目部分代碼:
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";}
}
有興趣的小伙伴,可以拿去看看,希望能在你編程學習的過程中幫助到你。
完整代碼和簡單的操作說明已經打包好了。可以獲取:
https://wwwoop.com/home/Index/projectInfo?goodsId=92&typeParam=2&subKey=1