web计算器

本文介绍了如何在web页面上创建一个支持基本运算的计算器。最初通过form表单提交到servlet并使用switch...case...处理运算,但这种方式不易扩展。后来采用反射机制改进,只需增加运算方法,实现了符合开闭原则的计算器。示例代码展示了前端html和servlet中仅包含加法操作,若要添加减法,只需在servlet中添加相应方法,反射将自动调用并返回结果。

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

在页面中实现一个具有+-×/功能的计算器,起初只是把form表单提交到servlet,然后把符号switch...case...,但是这样做不符合开闭原则,如果要增加运算符号,则会有很大的代码修改,最后有同学提出,可以用反射机制,这样只需要增加运算方法即可

前端html代码如下:

 <form action="calc" method="post">
		num1:<input type="text" name="num1" value="${sessionScope.num1 }" />
		<select name="method" id="method">
			<option value="add" id="add" >+</option>
			<option value="sub" id="sub">-</option>
			<option value="*" id="multiply">*</option>
			<option value="/" id="divide">/</option>
		</select>
		num2:<input type="text" name="num2" value="${sessionScope.num2 }" />
		<input type="submit" value="计算" id="submit" /><br /> 
	</form>
servlet代码如下:
package com.wzl.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CalcServlet extends HttpServlet {
	private static final long serialVersionUID = -3273567269240835150L;
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		System.out.println(method);
		Integer num1 = new Integer(req.getParameter("num1").trim());
		Integer num2 = new Integer(req.getParameter("num2").trim());
		Class calcClass = this.getClass();
		try {
 //反射,得到class中的方法,参数中method为方法名,后边接参数列表的类对象(注:Integer.class和int.class不一样)
			Method calcMethod = calcClass.getDeclaredMethod(method,Integer.class,Integer.class);
			if (calcMethod != null) {
				Object result= calcMethod.invoke(this, num1, num2);
				String message = String.format(method + "执行结果:%d", result);
				req.setAttribute("message", message);
				req.getRequestDispatcher("result.jsp").forward(req, resp);;
				
			}
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
			resp.sendError(500,"NoSuchMethod方法");
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	public Integer  add(Integer num1,Integer num2){
		return num1+num2;
	}
}

servlet类中,只写了增加(add)方法,如果需要增加减法运算的方法,只需要增加方法即可,类的反射会得到减法,并给出结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值