问题
This should be a simple Jsp servlet calculator wich insn't working. Maybe I am blind but I think I miss something. Can someone help me?
I have a servlet:
package com.service.servlet;
import java.io.IOException
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Calculator")
public class Calculator extends HttpServlet {
private static final long serialVersionUID = 1L;
double result;
public Calculator() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String valueString = request.getParameter("value");
String resultString = request.getParameter("result");
double result = 0;
if (!resultString.isEmpty()) {
result = Double.parseDouble(resultString);
}
if (!valueString.isEmpty()) {
double value = Double.parseDouble(valueString);
Map parameters = request.getParameterMap();
if (parameters.containsKey("plus")) {
result += value;
} else if (parameters.containsKey("minus")) {
result -= value;
} else if (parameters.containsKey("divide")) {
result /= value;
} else if (parameters.containsKey("multiply")) {
result *= value;
}
request.setAttribute("value", result);
RequestDispatcher view = request.getRequestDispatcher("/Calc.jsp");
view.forward(request, response);
} else {
RequestDispatcher view = request.getRequestDispatcher("/Calc.jsp");
view.forward(request, response);
}
}
}
The Jsp File is simple and clean with value and result:
<form action="Calculator" method="POST">
<input name="value" type="text"/>
<input name="plus" type="submit" value="+" />
<input name="minus" type="submit" value="-" />
<input name="divide" type="submit" value="/" />
<input name="multiply" type="submit" value="*" />
<input name="result" readonly="readonly" type="text" value="" />";
</form>
回答1:
You should change the setAttribute()
call to:
request.setAttribute("result", result);
Then modify the following line:
<input name="result" readonly="readonly" type="text" value="${result}" />;
来源:https://stackoverflow.com/questions/33484966/java-jsp-servlet-calculator