在Springboot下实现一个计算器实现简单的加减乘除功能

本文详细介绍了一个基于SpringBoot框架的前后端分离计算器应用。前端使用Ajax实现异步请求,展示输入框及计算结果;后端负责计算逻辑,通过接收前端发送的请求参数,完成加减乘除运算并返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求描述:

              前台显示一个基本的输入框和显示计算结果的框,用户输入基本的数据,选择相应的计算方式后,向后台发送请求;

后台获取相应的数据进行计算,向前台返回相应的结果。

1、项目框架内容

springboot项目

            

2、前台技术实现

使用ajax实现异步操作显示计算结果;

ajax的基本使用方式:https://www.cnblogs.com/caifenglin/p/7797811.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--<form action="/calculate" method="post">-->
    <table border="1">
        <tr>
            <td><input type="text" id="num1" placeholder="请输入第一个数"/></td>
            <td>
                <select id="operation">
                    <option value="+">+</option>
                    <option value="-">-</option>
                    <option value="*">*</option>
                    <option value="/">/</option>
                </select>
            </td>
            <td><input type="text" id="num2" placeholder="请输入第二个数"/></td>
            <td><input type="button" value="=" onclick="calculate();"/></td>
            <td><input type="text" name="result" id="result" />
            <!--<input th:text="${result}" />-->
            </td>
        </tr>
    </table>
    <input type="button" onclick="getResult()" value="获得结果"  />
<!--</form>-->
</body>
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript">

   /*function calculate() {

       var a = parseInt(document.getElementById("num1").value);
       var b = document.getElementById("operation").value;
       var c = parseInt(document.getElementById("num2").value);
       var result = '';
        switch (b) {
            case '+':
                result = a + c;
                alert(result);
                break;
            case '-':
                result = a - c;
                alert(result);
                break;
            case '*':
                result = a * c;
                alert(result);
                break;
            case '/':
                if (c != 0) {
                    result = a / c;
                    alert(result);
                }else{
                    alert("除法运算分母不能为0!");
                }
                break;
        }
       //设置输入框的计算结果
       document.getElementById("result").value = result;
    }*/
    function getResult() {
        var a = parseInt(document.getElementById("num1").value);
        var b = document.getElementById("operation").value;
        var c = parseInt(document.getElementById("num2").value);

        $.ajax({
            url:"/calculate",    //请求的url地址
            dataType:"json",   //返回格式为json
            async:true,//请求是否异步,默认为异步,这也是ajax重要特性
            data:{
                a:a,
                b:b,
                c:c
            },    //参数值
            type:"POST",   //请求方式
            success:function(req){
                //请求成功时处理
                // console.log(req)
                alert(req);
                document.getElementById("result").value=req;
            },
            error:function () {
                console.log("error");
            }
        });

    }

</script>

</html>

3、后台实现

将计算表达式对应的每一项,提取出来封装成一个类Expression

public class Expression implements Serializable {

    private Integer numOne;
    private Character operation;
    private Integer numTwo;
    
    //.....
}

在web层实现接收请求的方法,获取请求的参数并计算,向前台返回相应的结果。

@Controller
public class CalculateController {

    @PostMapping("/calculate")
    @ResponseBody
//    public Model calculate
    public String calculate( String a,Character b,String c/*, Model model*/){

        int num1 = Integer.parseInt(a);
        char oper = b;
        int num2 = Integer.parseInt(c);
        Expression expression = new Expression(num1,oper,num2);

        Integer result = 0;
        switch(oper){
            case '+':
                result = expression.getNumOne() + expression.getNumTwo();
                break;
            case '-':
                result = expression.getNumOne() - expression.getNumTwo();
                break;
            case '*':
                result = expression.getNumOne() * expression.getNumTwo();
                break;
            case '/':
                try{
                    if(expression.getNumTwo() != 0){
                        result = expression.getNumOne() / expression.getNumTwo();
                    }else{
                        throw new RuntimeException("除法运算,分母不能为0!");
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
                break;
        }
//        model.addAttribute("result",result);
//        System.out.println(a);
        return result.toString();
//        return model;
    }

拓展:

       spring、springmvc中Model返回类型的方式?

      参考链接:https://blog.youkuaiyun.com/qq_21223653/article/details/81365770

                       https://blog.youkuaiyun.com/Wanger_tt/article/details/50846912

       什么是json?以及阿里巴巴fastjson的详细使用方式(maven下导入依赖坐标)

       参考链接:https://blog.youkuaiyun.com/srj1095530512/article/details/82529759

spring mvc标单数据的获取:https://www.cnblogs.com/ChromeT/p/9964768.html

 

 

 

 

 

 

 

 

2 = 1.1904 整数部分为1,小数部分为0.1904 0.190采用基于注解的 AOP 实现切面编程的步骤如下: 1. 添加依赖:首先4 * 2 = 0.3808 整数部分为0,小数部分为0.3808 0,在项目中添加 AOP 相关的依赖,例如 Spring AOP、AspectJ 等。 2. 定义注解:定义.3808 * 2 = 0.7616 整数部分为0,小数部分为0.7616一个自定义注解,用于标识需要进行切面编程的方法。 ``` @Target(ElementType.METHOD) @ 0.7616 * 2 = 1.5232 整数部分为1,小数部分为0.Retention(RetentionPolicy.RUNTIME) public @interface Loggable { } ``` 3. 实现切面逻辑:编写一个切5232 0.5232 * 2 = 1.0464 整数部分为1,小数部分为0.0464 0.0464 * 2 = 0.0928 整数部分为0,小数部面类,实现切面逻辑和附加功能。在切面类中定义各种通知方法,例如前置分为0.0928 0.0928 * 2 = 0.1856 整数部分为0,小通知、后置通知、返回通知、异常通知等,并在相应的通知方法中添加日志记录数部分为0.1856 0.1856 * 2 = 0.3712 整数部分为0的逻辑。 ``` @Aspect @Component public class LoggingAspect { private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class); @Before("@annotation(Loggable)") public void beforeAdvice(JoinPoint joinPoint) { logger.info("Before method:,小数部分为0.3712 0.3712 * 2 = 0.7424 整数部分 {}", joinPoint.getSignature().getName()); } @After("@annotation(Loggable)") public void afterAdvice(JoinPoint joinPoint)为0,小数部分为0.7424 0.7424 * 2 = 1.4848 整数 { logger.info("After method: {}", joinPoint.getSignature().getName()); } @AfterReturning(pointcut = "@annotation(Loggable部分为1,小数部分为0.4848 0.4848 * 2 = 0.9696 )", returning = "result") public void afterReturningAdvice(JoinPoint joinPoint, Object result) { logger.info("After returning method 整数部分为0,小数部分为0.9696 0.9696 * 2 = 1.939: {}", joinPoint.getSignature().getName()); } @AfterThrowing(pointcut = "@annotation(Loggable)", throwing = "error") 2 整数部分为1,小数部分为0.9392 0.9392 * 2 = 1 public void afterThrowingAdvice(JoinPoint joinPoint, Throwable error) { logger.error("After throwing method: {}", joinPoint.get.8784 整数部分为1,小数部分为0.8784 0.8784 * 2 =Signature().getName(), error); } } ``` 4. 在目标方法上添加注解:在需要进行切面编程 1.7568 整数部分为1,小数部分为0.7568 0.7568 * 的方法上添加自定义注解。 ``` @Component public class Calculator { @Loggable public int add(int x,2 = 1.5136 整数部分为1,小数部分为0.5136 0.5136 int y) { return x + y; } @Loggable public int sub(int x, int y) { * 2 = 1.0272 整数部分为1,小数部分为0.0272 0. return x - y; } @Loggable public int mul(int x, int y) { return x * y; 0272 * 2 = 0.0544 整数部分为0,小数部分为0.0544 } @Loggable public int div(int x, int y) { return x / y; } } ``` 0.0544 * 2 = 0.1088 整数部分为0,小数部分为0.108在以上示例中,我们实现一个简单计算器,其中的 add、sub、mul、div 方法均8 0.1088 * 2 = 0.2176 整数部分为0,小数部分为0添加了自定义注解 @Loggable。 5. 测试:编写一个测试类,测试切面编程的效果。 .2176 0.2176 * 2 = 0.4352 整数部分为0,小数部分``` @RunWith(SpringRunner.class) @SpringBootTest public class AopApplicationTests { @Autowired private Calculator calculator; @Test为0.4352 0.4352 * 2 = 0.8704 整数部分为0,小数 public void testAdd() { int result = calculator.add(1, 2); assertEquals(3, result); } 部分为0.8704 0.8704 * 2 = 1.7408 整数部分为1,} ``` 在测试类中,我们通过调用计算器的 add 方法来测试切面编程的效果。当小数部分为0.7408 0.7408 * 2 = 1.4816 整数部分为 add 方法被调用时,将会触发 LoggingAspect 类中定义的各种通知方法,并在控制台中输出1,小数部分为0.4816 0.4816 * 2 = 0.9632 整数部日志信息。 以上就是采用基于注解的 AOP 实现切面编程的步骤,通过这种分为0,小数部分为0.9632 0.9632 * 2 = 1.9264 整方式,我们可以很方便地实现切面编程,并在通知方法中添加各种附加功能,例如日志记录、性能监控等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值