用jsp中做一个登录页面,用request对象设计实现一个简单的计算加减乘除运算的网页程序
时间: 2023-05-24 16:00:50 浏览: 199
可以使用jsp中的表单和servlet来实现计算加减乘除运算的网页程序。首先,在jsp页面中创建一个表单,包括运算符和两个操作数的输入框。设置提交按钮的action为一个处理表单数据的servlet。在servlet中,使用request对象获取表单提交的数据,进行相应的运算,并将结果存储在request对象中,然后转发给显示结果的jsp页面。具体实现可以参考以下代码:
login.jsp:
```
<form action="calculate" method="post">
Operand 1: <input type="text" name="operand1"><br>
Operand 2: <input type="text" name="operand2"><br>
Operator:
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br>
<input type="submit" value="Submit">
</form>
```
CalculateServlet.java:
```
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CalculateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int operand1 = Integer.parseInt(request.getParameter("operand1"));
int operand2 = Integer.parseInt(request.getParameter("operand2"));
String operator = request.getParameter("operator");
int result = 0;
if (operator.equals("+")) {
result = operand1 + operand2;
} else if (operator.equals("-")) {
result = operand1 - operand2;
} else if (operator.equals("*")) {
result = operand1 * operand2;
} else if (operator.equals("/")) {
result = operand1 / operand2;
}
request.setAttribute("result", result);
request.getRequestDispatcher("result.jsp").forward(request, response);
}
}
```
result.jsp:
```
Result: <%= request.getAttribute("result") %>
```
阅读全文