• 基于Servlet+jsp的web计算器


    基于Servlet+jsp的web计算器

    这次老大为了让我们自己复习web中页面的跳转给布置得任务

    天下代码一大抄,关键看你怎么抄

    首先我想到的计算算法不是什么堆栈,是简单的(其实很复杂,但是我就只需要知道有这个东西,东西别人做好了...传说中的CV大法好?Emmm,当你知道有这么个算法但是不会自己写可是自己会用的时候,也就相当于...自己会了.....)

    图片

    废话不多说一下是收集的正则工具类,支持括号运算

    package pers.cal.util;
    
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
     
    public class UtilArithmetic {
    //    public static void main(String[] args) {
    //        String src = "(3 + (5 - 2) * 10 / 2 * 3 + 15) * (8 - 4)";
    //        System.out.println(cal(src));
    //    }
        public static String cal(String src) {
            StringBuilder builder = new StringBuilder();
            if (src.contains("(")) {
                Pattern pattern = Pattern.compile("\(([^()]+)\)");
                Matcher matcher = pattern.matcher(src);
                int lastEnd = 0;
                while (matcher.find()) {
    				
                    builder.append(src.substring(lastEnd, matcher.start()));
    				System.out.println(builder.toString());
                    builder.append(cal(matcher.group(1)));
                    lastEnd = matcher.end();
                }
                builder.append(src.substring(lastEnd));
            } else {
                Pattern pattern = Pattern.compile("([\d.]+)\s*([*/])\s*([\d.]+)");
                builder.append(src);
                Matcher matcher = pattern.matcher(builder.toString());
                while (matcher.find()){
                    float f1 = Float.parseFloat(matcher.group(1));
                    float f2 = Float.parseFloat(matcher.group(3));
                    float result = 0;
                    switch (matcher.group(2)){
                        case "*":
                            result = f1 * f2;
                            break;
                        case "/":
                            result = f1 / f2;
                            break;
                    }
                    builder.replace(matcher.start(), matcher.end(),
                            String.valueOf(result));
                    matcher.reset(builder.toString());
                }
                pattern = Pattern.compile("([\d.]+)\s*([+-])\s*([\d.]+)");
                matcher = pattern.matcher(builder.toString());
                while (matcher.find()){
                    float f1 = Float.parseFloat(matcher.group(1));
                    float f2 = Float.parseFloat(matcher.group(3));
                    float result = 0;
                    switch (matcher.group(2)){
                        case "+":
                            result = f1 + f2;
                            break;
                        case "-":
                            result = f1 - f2;
                            break;
                    }
                    builder.replace(matcher.start(), matcher.end(),
                            String.valueOf(result));
                    matcher.reset(builder.toString());
                }
                return builder.toString();
            }
            System.out.println(builder);
            return cal(builder.toString());
        }
    }
    
    

    调用的时候直接用cal(String str)就好

    然后是对应的前台jsp

    <%@ page language="java" contentType="text/html; charset=utf-8"
    	pageEncoding="utf-8"%>
    	<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>基于Servlet+jsp的Web计算器的项目</title>
    
    <link href="./css/index.css" rel="stylesheet" type="text/css" />
    
    <script type="text/javascript">
    	var cleartext = false;//设置标识值
    	function getNum(num) {
    		//alert(num);
    		var result = document.getElementById("result");
    		if (cleartext) {
    			result.value = "";
    			//cleartext = false;
    		}
    		result.value += num;
    	}
    
    	function getResult() {
    		var result = document.getElementById("result");
    		//result.value=result.value+"="+eval(result.value);
    		//next is the str we need
    		result.value = result.value;
    		//this result.value is the str we need
    		//alert(result.value);
    		//cleartext = true;//计算结果后改变标识
    	}
    </script>
    </head>
    <body>
    	<div class="calculator">
    		<span class="copyRight">金 聖 聰 ®</span>
    
    		<form action="calculator.do" method="post" name="From"
    			onclick="return getResult">
    
    			<div class="calculator-display">
    				<input type="text" name="result" id="result" size="33"
    					readonly=readonly value="${ count}" >
    			</div>
    
    			<div class="calculator-keys">
    				<button type="button" class="all-clear" value="all-clear"
    					onclick="document.getElementById('result').value=''">AC</button>
    
    				<button type="button" value="9" onclick="getNum('(')">(</button>
    				<button type="button" value="9" onclick="getNum(')')">)</button>
    				<button type="button" class="operator" value="+"
    					onclick="getNum('+')">+</button>
    
    				<button type="button" value="7" onclick="getNum(7)">7</button>
    				<button type="button" value="8" onclick="getNum(8)">8</button>
    				<button type="button" value="9" onclick="getNum(9)">9</button>
    
    				<button type="button" class="operator" value="-"
    					onclick="getNum('-')">-</button>
    				<button type="button" value="4" onclick="getNum(4)">4</button>
    				<button type="button" value="5" onclick="getNum(5)">5</button>
    				<button type="button" value="6" onclick="getNum(6)">6</button>
    				<button type="button" class="operator" value="*"
    					onclick="getNum('*')">&times;</button>
    
    				<button type="button" value="1" onclick="getNum(1)">1</button>
    				<button type="button" value="2" onclick="getNum(2)">2</button>
    				<button type="button" value="3" onclick="getNum(3)">3</button>
    
    				<button type="button" class="operator" value="/"
    					onclick="getNum('/')">&divide;</button>
    				<button type="button" value="0" onclick="getNum(0)">0</button>
    				<button type="button" class="decimal" value="."
    					onclick="getNum('.')">.</button>
    				<button class="equal-sign" value="=" onclick="getResult('.')">=</button>
    			</div>
    
    		</form>
    	</div>
    
    
    </body>
    </html>
    

    他的css

    html {
        font-size: 62.5%;
        box-sizing: border-box;
        margin: 0;
        padding: 0;
        box-sizing: inherit
    }
    
    body {
       100vw;
      min-height: 100vh;
      background-color: #B0C4DE;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .calculator {
      background: #1d1e22;
      padding:2.8rem .64rem .64rem;
      color: white;
      border-radius: .5rem;
      box-shadow: 0 .3rem 3rem .1rem rgba(0,0,0,0.6);
      position: relative;
      min- 40rem;
    }
    
    .calculator-display {
      font-size: 5rem;
      height: 80px;
      padding: 0 20px;
      background-color: #1d1e22;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      
    }
     #result{
    	color:white; 
    	background-color:#003300;
    	100%;
    	height:50%;
    	font-size:33%;
    	text-align:right;
    }
    button {
      height: 60px;
      border-radius: 3px;
      border: 1px solid #c4c4c4;
      font-size: 2rem;  
      background-color: #fff;
    
    }
    
    .calculator-keys {
      display: grid;
      grid-gap: 2rem;
      padding: 2rem 1.36rem;
      background-color: #fff;
    }
    
    .equal-sign {
      grid-row: 5 / span 1;
      grid-column: 3 / 5;
      height: 100%;
    }
    .copyRight{
    	text-align: center;
    	display:block;
    	color:black;
    	font-weight:bolder;
    	font-size: 33px;
    }
    

    长这个样子

    图片

    用到了El表达式

    相关jar包

    图片

    xml配置

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns="http://java.sun.com/xml/ns/javaee"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    	id="WebApp_ID" version="2.5">
    	<display-name>Calculation</display-name>
    
    	<servlet>
    		<servlet-name>ServletDemo</servlet-name>
    		<servlet-class>pers.cal.servlet.CalculationServlet</servlet-class>
    	</servlet>
    
    	<servlet-mapping>
    		<servlet-name>ServletDemo</servlet-name>
    		<url-pattern>/calculator.do</url-pattern>
    	</servlet-mapping>
    </web-app>
    

    对应的Servlet

    package pers.cal.servlet;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import pers.cal.util.UtilArithmetic;
    
    public class CalculationServlet extends HttpServlet {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		doPost(req, resp);
    	}
    	
    	
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	
    		String result = req.getParameter("result");
    	//	req.setAttribute("result", "admin");
    		String finalRes = result;
    		result = finalRes+"="+UtilArithmetic.cal(result);
    		
    		HttpSession session = req.getSession();
    		session.setAttribute("count",result);
    		System.out.println(result);
    		req.getRequestDispatcher("index.jsp").forward(req, resp);
    	}
    
    	
    }
    
    

    最后是结构

    图片

    晚安。

    做个好梦

    おやすみ~

  • 相关阅读:
    InvalidIndexNameException[Invalid index name [2Shard], must be lowercase]
    Head插件——学习Elasticsearch的锋刃利器!
    Fiddler使用AutoResponder进行本地文件和线上文件的映射
    启动redis出现Creating Server TCP listening socket *:6379: bind: No such file or directory
    Project configuration is not up-to-date with pom.xml错误解决方法
    创建支持eclipse的多模块maven项目
    Eclipse添加默认的JRE
    错误:HttpServlet was not found on the Java
    Android插件化开发之Atlas初体验
    Android屏幕适配全攻略(最权威的官方适配指导)
  • 原文地址:https://www.cnblogs.com/jsccc520/p/10325489.html
Copyright © 2020-2023  润新知