我试图把我的头缠在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
然而,我没有得到结果。
你能告诉我我做错了什么吗?
1条答案
按热度按时间yrefmtwq1#
看看你的动作
您需要将操作指向servlet,而不是JSP。