使用jsp设计网页计算器添加报错处理异常
时间: 2024-12-19 14:15:24 浏览: 10
使用jsp调用javabean实现超简单网页计算器示例
5星 · 资源好评率100%
在使用JSP设计网页计算器并添加错误处理异常时,你可以遵循以下步骤:
1. **页面布局**:
创建一个基本的HTML结构,包含输入框用于用户输入数字和操作符,以及提交按钮。例如,可以有`<input type="text">`用于显示结果,`<button>`标签用于触发计算。
```html
<form action="calculator.jsp" method="post">
<input id="num1" type="number" name="num1"><br>
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select><br>
<input id="num2" type="number" name="num2"><br>
<input type="submit" value="Calculate">
<span id="result"></span>
<span id="error-message" style="color:red;"></span>
</form>
```
2. **服务器端Java(JSP)处理**:
在`calculator.jsp`文件中,创建一个Java bean(如CalculatorBean),包含计算方法,并捕获可能出现的异常。
```java
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="result" value="" scope="request"/>
<c:set var="errorMessage" value="" scope="request"/>
<script>
function calculate() {
// 异步获取表单数据
var num1 = document.getElementById("num1").value;
var operator = document.querySelector('select[name=operator]').value;
var num2 = document.getElementById("num2").value;
// 调用后台方法进行计算
$.ajax({
url: "calculate",
data: {num1: num1, operator: operator, num2: num2},
success: function(response) {
result = response.result;
document.getElementById("result").innerHTML = result;
},
error: function(xhr, status, error) {
errorMessage = xhr.responseText; // 获取错误信息
document.getElementById("error-message").innerHTML = errorMessage;
}
});
}
</script>
...
<body>
<!-- ... -->
<c:if test="${not empty errorMessage}">
<p>Error: ${errorMessage}</p>
</c:if>
<input onclick="calculate()" type="button" value="Calculate">
<p>Result: ${result}</p>
</body>
</jsp>
```
3. **错误处理部分**:
在Servlet或Controller中(如果使用的是MVC架构),对用户输入进行检查,比如防止除数为零、验证数字格式等,并抛出对应的异常。然后在相应处理方法中捕获异常,返回错误消息给前端。
```java
// Servlet example
@WebServlet("/calculate")
public class CalculatorServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String num1 = request.getParameter("num1");
String operator = request.getParameter("operator");
String num2 = request.getParameter("num2");
CalculatorBean calculator = new CalculatorBean();
try {
double result = calculator.calculate(num1, num2, operator);
request.setAttribute("result", result);
} catch (IllegalArgumentException e) {
request.setAttribute("errorMessage", "Invalid input: " + e.getMessage());
}
request.getRequestDispatcher(request.getServletPath()).forward(request, response);
}
}
// Java Bean Example
public class CalculatorBean {
public double calculate(String num1, String num2, String operator) throws IllegalArgumentException {
// ... Perform calculations and validate inputs
if (operator.equals("/") && Double.parseDouble(num2) == 0) {
throw new IllegalArgumentException("Cannot divide by zero.");
}
// ...
}
}
```
阅读全文