使用Servlet+JSP实现简单计算器功能,主要要求如下: Input.jsp:两个数据的输入及运算符的选择,并提交. Calculator.java:根据选择的运算符计算两个数的运算结果,并将结果转发到最终结果页面Result.jsp.使用RequestDispatcher对象实现转发. Result.jsp:显示最终结果. 请按顺序补全以下空格处代码: Input.jsp: + - * / Calculator.java: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); float num1 = _______________3________________; float num2 =______________ _4________________; String op=_________________5________________; float num3=0; if(op.equals("1")) { num3=num1+num2; }else if(op.equals("2")) { num3=num1-num2; }else if(op.equals("3")) { num3=num1*num2; }else { _________________6_________________; } ServletContext context = _______7_______; RequestDispatcher rd = context._______8_______("/Result.jsp?result="_______9_______); rd._______10_______; }
时间: 2024-01-05 11:02:45 浏览: 187
Input.jsp:
```html
<form action="Calculator" method="post">
<input type="text" name="num1">
<select name="op">
<option value="1">+</option>
<option value="2">-</option>
<option value="3">*</option>
<option value="4">/</option>
</select>
<input type="text" name="num2">
<br>
<input type="submit" value="Calculate">
</form>
```
Calculator.java:
```java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
float num1 = Float.parseFloat(request.getParameter("num1"));
float num2 = Float.parseFloat(request.getParameter("num2"));
String op = request.getParameter("op");
float num3 = 0;
if(op.equals("1")) {
num3 = num1 + num2;
} else if(op.equals("2")) {
num3 = num1 - num2;
} else if(op.equals("3")) {
num3 = num1 * num2;
} else {
if(num2 == 0) {
response.sendRedirect("error.jsp");
return;
} else {
num3 = num1 / num2;
}
}
ServletContext context = getServletContext();
RequestDispatcher rd = context.getRequestDispatcher("/Result.jsp?result=" + num3);
rd.forward(request, response);
}
```
其中,空格处需要填写的代码如下:
1. `Float.parseFloat(request.getParameter("num1"))`
2. `Float.parseFloat(request.getParameter("num2"))`
3. `request.getParameter("num1")`
4. `request.getParameter("num2")`
5. `request.getParameter("op")`
6. `response.sendRedirect("error.jsp"); return;`
7. `getServletContext()`
8. `getRequestDispatcher`
9. `+ num3`
10. `forward(request, response)`
阅读全文