基于Servlet+jsp的web计算器

Posted 故事我忘了°

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于Servlet+jsp的web计算器相关的知识,希望对你有一定的参考价值。

基于Servlet+jsp的web计算器

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

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

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

技术分享图片

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

package pers.cal.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 正则表达式实现的计算器带括号版本
 * @author Administrator
 *
 */
public class UtilArithmetic {
    /**
     * 计算可能含有括号的表达式
     * 
     * @param s
     * @return
     */
    public static String calcu(String s) {

        s = s.replaceAll(" +", "");// 消除空格,空格可以是一个或多个,找到就替换
        // \(为左括号 \)右括号,表示在括号内没有其他括号,然后用括号括起来是一个子组e
        Pattern pa = Pattern.compile("\(([^\(\)]*)\)");
        while (true) {
            Matcher ma = pa.matcher(s);
            if (ma.find() == false)
                break;
            // 先计算括号内,然后消除括号
            s = s.replace(ma.group(), calcuNoParen(ma.group(1)));
        }

        return calcuNoParen(s);
    }

    /**
     * 计算没有括号的运算
     * 
     * @param s2
     * @return
     */
    public static String calcuNoParen(String s2) {
        if (s2.length() < 1)
            return s2;
        // 先把乘法消除
        Pattern pat = Pattern.compile("([0-9]+)\*([0-9]+)");//0-9一个或多个,乘法
        while (true) {
            Matcher mc = pat.matcher(s2);
            if (mc.find() == false)
                break;
            int res = Integer.parseInt(mc.group(1)) * Integer.parseInt(mc.group(2));
            // 计算出结果,并且消除括号,注意这里不能用replaceAll
            s2 = s2.replace(mc.group(), res + "");
        }
        // 再从左到右消除所有加法和减法
        pat = Pattern.compile("([0-9]+)([\+\-])([0-9]+)");// 0-9一个或多个,加法或者减法
        while (true) {
            Matcher mc = pat.matcher(s2);
            if (mc.find() == false)
                break;
            int res = 0;
            switch (mc.group(2)) {
            case "+":
                res = Integer.parseInt(mc.group(1)) + Integer.parseInt(mc.group(3));
                break;

            case "-":
                res = Integer.parseInt(mc.group(1)) - Integer.parseInt(mc.group(3));
                break;
            }
            // 计算出结果,并且消除括号,注意这里不能用replaceAl
            s2 = s2.replace(mc.group(), res + "");
        }
        return s2;
    }

}

调用的时候直接用calcu()就好

然后是对应的前台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 {
  width: 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-width: 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;
    width: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.calcu(result);
        
        HttpSession session = req.getSession();
        session.setAttribute("count",result);
        System.out.println(result);
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    
}

最后是结构

技术分享图片

晚安。

做个好梦

おやすみ~

以上是关于基于Servlet+jsp的web计算器的主要内容,如果未能解决你的问题,请参考以下文章

JSP基础学习

java web开发入门一(servlet和jsp)基于eclispe

Java web中使用到的技术

熟悉基于JSP和Servlet的Java Web开发,对Servlet和JSP的工作原理和生命周期有深入了解,熟练的使用JSTL和EL编写无脚本动态页面,有使用监听器过滤器等Web组件以及MVC架构

JSP 学习总结---学习笔记

计算机毕业设计-基于javaweb的外卖点餐系统-基于jsp的外卖系统源代码-校园外卖点餐系统java-骑手送外卖商家统计项目代码