Issue
I'm trying to wrap my head around servlets and JSP and I got stuck when implementing a simple calculator.
Basically, I have two input fields, operator selection field and the submit button.
When I click on the submit button I need to perform the chosen arithmetic operation on two values from input elements and show the result on the same page.
Here's what I have:
<!-- hello.jsp page -->
<form action="hello.jsp" id="calc-form">
<input type="number" name="num1" required>
<select id="opers" name="oper">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="number" name="num2" required>
<input type="submit" value="Calculate">
</form>
<h2>The result is: ${result}</h2>
my doGet
method in hello
servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
System.out.println("Hello#doGet");
String strNum1 = request.getParameter("num1");
String strNum2 = request.getParameter("num2");
String oper = request.getParameter("oper");
double a, b, result = 0;
if(validateNum(strNum1) && validateNum(strNum2) && validateOper(oper)) {
try {
a = Double.parseDouble(request.getParameter("num1"));
b = Double.parseDouble(request.getParameter("num2"));
switch(oper) {
case "+":
result = a + b;
break;
case "-":
result = a - b;
break;
case "*":
result = a * b;
break;
case "/":
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed");
} else {
result = a / b;
}
}
} catch(NumberFormatException | ArithmeticException e) {
// handle the exception somehow
}
request.setAttribute("result", result);
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/hello.jsp");
dispatcher.forward(request, response);
}
So, when I go to http://localhost:8080/test2/hello
, enter the numbers in input elements and press submit, I get redirected to address that looks pretty much like this:
http://localhost:8080/test2/hello.jsp?num1=4&oper=*&num2=4
however, I don't get the result.
Could you please tell me what I'm doing wrong here?
Solution
Look at your action
<form action="hello.jsp" id="calc-form">
You need to point your action to the servlet. not JSP.
Answered By - Suresh Atta
Answer Checked By - Terry (JavaFixing Volunteer)