Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Two Numbers</title>
</head>
<body>
<h1>Please enter numbers</h1>
<form action="AddNum" method="post">
Enter 1st Number :<br>
<input type=text name=num1><br><br>
Enter 2nd Number :<br>
<input type=text name=num2><br><br>
<input type="submit">
</form>
</body>
</html>
Here is the java code:
package com.package1;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/AddNum")
public class Addserv extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
int no1=Integer.parseInt(req.getParameter("num1"));
int no2=Integer.parseInt(req.getParameter("num2"));
int sum=no1+no2;
PrintWriter out = resp.getWriter();
out.println(sum);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}
even though I used the doPost
method, I am getting this error message.
I am using Eclipse for IDE and Apache Tomcat 10.1.30 as my server
I tried to add a doget
method(still in code as I believe it doesn't negatively alter anything)
Tried changing the method of the form to "get"
, same 405 error with get instead of post.
The default implementation of doPost
is to return an HTTP 405 error, and it should be overridden to get a different behavior. However, by calling super.getPost
, you're generating that error again.
Long story short - remove the call to the super's method and you should be OK:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// call to super.doPost remove from here
int no1=Integer.parseInt(req.getParameter("num1"));
int no2=Integer.parseInt(req.getParameter("num2"));
int sum=no1+no2;
PrintWriter out = resp.getWriter();
out.println(sum);
}