但我希望得到结果页面(calculatorResult.jsp)。
当我使用calculator.jsp作为index.jsp(没有"欢迎页面")一切正常。
我的servlet代码。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/calculator")
public class CalculatorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int number1 = Integer.parseInt(req.getParameter("no1"));
int number2 = Integer.parseInt(req.getParameter("no2"));
String operation = req.getParameter("operation");
int result = 0;
if (operation.equals("plus")) {
result = number1 + number2;
} else if (operation.equals("minus")) {
result = number1 - number2;
}
req.setAttribute("result", Integer.valueOf(result));
req.getRequestDispatcher("/calculatorResult.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
的index.jsp
<html>
<head>
<title>Hello</title>
</head>
<body>
<div style="text-align: center">
<form>
<input type="button" value="Calculator" onClick='location.href="calculator.jsp"'>
</form>
</div>
</a>
</body>
</html>
calculator.jsp
<html>
<div style="text-align: center;">
<br>
<br>
<br>
<form method="get" action="CalculatorServlet">
Number 1: <input type="number" name="no1"> <br>
Number 2: <input type="number" name="no2"> <br>
Operator:
<select name="operation">
<option value="plus">+</option>
<option value="minus">-</option>
</select>
<br>
<input type="submit" value="Calculate">
</form>
</div>
</body>
</html>
calculatorResult.jsp
<html>
<head>
<title>Result</title>
</head>
<body>
<h1>Result: ${result}</h1>
<br>
<a href="calculator.jsp">Back to calculator</a>
</body>
</html>
请帮我解决这个问题。