您现在的位置是:首页 > 文章详情

Spring Boot入门(9)网页版计算器

日期:2018-04-23点击:696

介绍

在写了前八篇Spring Boot项目的介绍文章后,我们已经初步熟悉了利用Spring Boot来做Web应用和数据库的使用方法了,但是这些仅仅是官方介绍的一个例子而已。
本次分享将介绍笔者自己的一个项目:网页版计算器,以这两篇博客为基础: Java之调用Python代码Spring Boot入门(6)前端接受后台传参。因为在Java中并没有类似于Python的eval()函数的功能,所以,为了避免自己写一个计算数学表达式的java代码,我们的解决方法是:用Java调用Python代码来实现。
话不多说,直接上项目!

项目

网页版计算器的整个项目结构如下图:


整个项目结构

Expression.java为实体类,用于页面中表单提交的数学表达式的处理,其代码如下:

package com.hello.operation.Controller; public class Expression { private String expr; public String getExpr() { return expr; } public void setExpr(String expr) { this.expr = expr; } }

控制器文件ExpressionController.java的代码如下:

package com.hello.operation.Controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import java.util.Map; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; @Controller public class ExpressionController { @GetMapping("/mathoper") public String greetingForm(Model model) { model.addAttribute("expression", new Expression()); return "operation"; } @PostMapping("/mathoper") public String greetingSubmit(@ModelAttribute Expression expression, Map<String, Object> map) throws Exception { System.out.println(expression.getExpr()); // 定义传入shell脚本的参数,将参数放入字符串数组里 String expr = expression.getExpr(); String file_path = "D://eval.py"; String command = String.format("python %s %s", file_path, expr); // 执行CMD命令 System.out.println("\nExecuting python script file now ......"); Process pcs = Runtime.getRuntime().exec(command); pcs.waitFor(); // 定义shell返回值 String result = null; // 获取shell返回流 BufferedInputStream in = new BufferedInputStream(pcs.getInputStream()); // 字符流转换字节流 BufferedReader br = new BufferedReader(new InputStreamReader(in)); // 这里也可以输出文本日志 String lineStr = null; while ((lineStr = br.readLine()) != null) { result = lineStr; } // 关闭输入流 br.close(); in.close(); System.out.println(result); if(result.indexOf("Error") == -1) map.put("answer", "The answer is "+result); else map.put("answer", "<mark>"+result+"</mark>"); return "operation"; } }

在该代码中,调用了D盘下的eval.py来处理网页表达提交的数学表达式。Java提供的runtime环境可以运行eval.py文件,并获取CMD中的输出结果,即为计算结果,并将其通过Map方式返回前端。eval.py的代码如下:

import sys import math oper = sys.argv[1] try: print(eval(oper)) except Exception as e: print('Error: ', end='') print(e)

代码处理十分简洁,并引入math模块,可以处理复杂的数学运算。
接着是视图文件operation.html,其代码如下:

<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Math Operation</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <style> mark { background-color:#FF0000; font-weight:bold; } </style> </head> <body> <center> <br><br> <h2 style="color:red">Math Operation</h2> <br><br> <form class="form-horizontal" role="form" action="#" th:action="@{/mathoper}" th:object="${expression}" method="post"> <div class="form-group" style="width:500px"> <label for="expression" class="col-sm-4 control-label">Math Expression:</label> <div class="col-sm-8"> <input type="text" th:field="*{expr}" class="form-control" id="expression" placeholder="Enter a expression"> </div> </div> <div class="form-group"> <div> <button type="submit" class="btn btn-primary" id="btn">Show Answer</button> <input type="reset" class="btn btn-warning" value="Reset" /> </div> </div> </form> <p th:utext="${answer}"></p> </center> </body> </html>

整个项目的结构就是这样。

运行及测试

启动Spring Boot项目,并在浏览器中输入http://localhost:8080/mathoper ,页面显示如下:


网页版计算器

在输入框中输入(1+2)*3/4,点击“Show Answer”按钮,结果如下:


计算表达式1

当然也可以处理更加复杂的数学表达式,但是要符合Python的语法,如下图:


计算表达式2

当我们表达式出错时,也会提出Python的错误处理情况,如下图:


表达式输入错误

结束语

本次项目的Github地址为: https://github.com/percent4/MathOperation , 欢迎大家参考~~接下来还会继续更新更多关于Spring Boot方面的内容,欢迎大家交流~

原文链接:https://yq.aliyun.com/articles/615215
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章