web计算器
在页面中实现一个具有+-×/功能的计算器,起初只是把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)方法,如果需要增加减法运算的方法,只需要增加方法即可,类的反射会得到减法,并给出结果