【发布时间】:2016-01-08 10:27:10
【问题描述】:
我正试图围绕 servlet 和 JSP 进行研究,但在实现一个简单的计算器时遇到了困难。
基本上,我有两个输入字段,运算符选择字段和提交按钮。
当我点击提交按钮时,我需要对输入元素中的两个值执行所选算术运算,并将结果显示在同一页面上。
这是我所拥有的:
<!-- hello.jsp page -->
<form action="hello.jsp" id="calc-form">
<input type="number" name="num1" required>
<select id="opers" name="oper">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="number" name="num2" required>
<input type="submit" value="Calculate">
</form>
<h2>The result is: ${result}</h2>
hello servlet 中的我的doGet 方法:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
System.out.println("Hello#doGet");
String strNum1 = request.getParameter("num1");
String strNum2 = request.getParameter("num2");
String oper = request.getParameter("oper");
double a, b, result = 0;
if(validateNum(strNum1) && validateNum(strNum2) && validateOper(oper)) {
try {
a = Double.parseDouble(request.getParameter("num1"));
b = Double.parseDouble(request.getParameter("num2"));
switch(oper) {
case "+":
result = a + b;
break;
case "-":
result = a - b;
break;
case "*":
result = a * b;
break;
case "/":
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed");
} else {
result = a / b;
}
}
} catch(NumberFormatException | ArithmeticException e) {
// handle the exception somehow
}
request.setAttribute("result", result);
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/hello.jsp");
dispatcher.forward(request, response);
}
所以,当我转到http://localhost:8080/test2/hello,在输入元素中输入数字并按提交时,我会被重定向到看起来很像这样的地址:
http://localhost:8080/test2/hello.jsp?num1=4&oper=*&num2=4
但是,我没有得到结果。
你能告诉我我在这里做错了什么吗?
【问题讨论】:
标签: java jsp jakarta-ee servlets