在spring boot中用post请求写出四则混合运算代码,写出三种这样的代码
时间: 2024-09-18 08:07:31 浏览: 46
在Spring Boot中,我们通常使用`@RestController`和`@PostMapping`来处理HTTP POST请求,并可以利用`@RequestBody`来获取客户端发送的数据。以下是三个示例,展示如何实现四则混合运算的POST请求处理:
### 示例1:
```java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MathCalculatorController {
@PostMapping("/calculate")
public String calculate(@RequestBody String formula) {
String[] parts = formula.split(" ");
double leftNum = 0, rightNum = 0;
String operator;
try {
leftNum = Double.parseDouble(parts[0]);
operator = parts[1];
rightNum = Double.parseDouble(parts[2]);
switch (operator) {
case "+":
return Double.toString(leftNum + rightNum);
case "-":
return Double.toString(leftNum - rightNum);
case "*":
return Double.toString(leftNum * rightNum);
case "/":
if (rightNum != 0) {
return Double.toString(leftNum / rightNum);
} else {
return "Error: Division by zero";
}
default:
return "Error: Invalid operator";
}
} catch (NumberFormatException e) {
return "Error: Invalid number format";
}
}
}
```
### 示例2:
```java
@PostMapping("/calculate-with-validation")
public ResponseEntity<String> validateAndCalculate(@Valid @RequestBody CalculateRequest request) {
double result = request.calculate();
return ResponseEntity.ok().body(Double.toString(result));
}
class CalculateRequest {
private double num1;
private String operator;
private double num2;
// getters and setters
public double calculate() {
switch (operator) {
// ...同样处理四则运算
}
}
}
```
### 示例3:
```java
@RestController
public class AdvancedMathController {
@PostMapping("/complex-calculation")
public Result complexCalculation(@RequestBody CalculationData data) {
// 数据验证
if (!data.isValid()) {
return new Result(false, "Invalid input");
}
// 计算逻辑
double result = calculate(data.getExpression());
return new Result(true, result);
}
private double calculate(String expression) {
// 使用正则表达式解析并计算
}
static class CalculationData {
private String expression;
// getters and setters
// 提供验证逻辑
}
}
```
在这几个例子中,用户可以通过POST请求发送一个包含数字和运算符的字符串到指定的URL,服务器会解析这个字符串并执行相应的运算。每个示例都有其特定的结构和复杂度,比如第二个示例增加了输入验证和对象封装,第三个示例则展示了更复杂的表达式和数据结构处理。
阅读全文