所以我正在研究如何在Tomcat上部署一些基于Web的应用程序,到目前为止,我已经在Web服务器上运行了一个简单的webapp(localhost:8080 / Calculator-1.0-SNAPSHOT /)。
但是,我需要有关应用程序本身的帮助。它不显示计算结果。其他功能虽然有效,但不接受十进制数字。代码可以在这里找到:https://github.com/kirillrublevsky/Calculator
我的控制器中有以下代码:
package com.kirillrublevsky.app.controller;
import com.kirillrublevsky.app.service.CalculatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class CalculatorController {
@Autowired
private CalculatorService calculatorService;
@ResponseBody
@RequestMapping(value = "/calculate", method = RequestMethod.POST)
public double calculate(@RequestParam(value = "first", required = true) double first,
@RequestParam(value = "operation", required = true) String operation,
@RequestParam(value = "second", required = true) double second) {
return calculatorService.calculate(first, operation, second);
}
}
这是CalculatorService代码:
package com.kirillrublevsky.app.service.impl;
import com.kirillrublevsky.app.service.CalculatorService;
import org.springframework.stereotype.Service;
@Service
public class CalculatorServiceImpl implements CalculatorService {
@Override
public double calculate(double first, String operation, double second) {
double result = 0.0;
switch (operation) {
case "+":
result = first + second;
break;
case "-":
result = first - second;
break;
case "*":
result = first * second;
break;
case "/":
result = first / second;
break;
}
return result;
}
}
这是.js脚本:
/* jQuery and AJAX */
$(document).ready(function () {
$("#calculate").click(function (e) {
e.preventDefault();
var first = parseFloat($("#first").val());
var second = parseFloat($("#second").val());
var operation = $("#operation").find("option:selected").text();
$.ajax({
type: "POST",
url: "/calculate",
data: {"first": first, "operation": operation, "second": second},
success: function (data) {
$("#result").text(data);
}
});
});
});
和index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/resources/css/vendor/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="/resources/css/style.css"/>
</head>
<body>
<div class="container">
<form class="form-inline" role="form">
<div class="form-group">
<input type="number" class="form-control" id="first" required>
</div>
<div class="form-group">
<select class="form-control" id="operation">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
</div>
<div class="form-group">
<input type="number" class="form-control" id="second" required>
</div>
<span id="output"> = <span id="result">0.0</span></span>
</form>
<button id="calculate" type="submit" class="btn btn-danger btn-lg">Calculate</button>
</div>
<script src="/resources/js/vendor/jquery.min.js"></script>
<script src="/resources/js/vendor/bootstrap.min.js"></script>
<script src="/resources/js/app.js"></script>
</body>
</html>