Search code examples
javaeclipseservletstomcat7http-status-code-405

eclipse ee servlet tomcat doPost http405


I'm trying to go a post from HTML to Java Servlet using eclipse ee and tomcat starting the server through eclipse. But I am getting: HTTP Status 405 - HTTP method POST is not supported by this URL

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

</script>
</head>
<body>
<form method="POST" action="AddHost">
Host name : <input name="hostname" type="text"><br>
Genre : <input name="genre" type="text" ><br>
<input type="submit" value="add host">
</form>
</body>

</html>

This is the servlet:

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
@WebServlet("/AddHost")
public class Addhost extends HttpServlet {

    public void doPost(HttpServletResponse res,HttpServletRequest req) throws IOException{
        String hostname = req.getParameter("hostname");
        String genre = req.getParameter("genre");


    }
    public void doGet(HttpServletResponse res,HttpServletRequest req) throws IOException{
        doPost(res,req);
    }

Solution

  • You have used bad signature of method doPost and instead of overriding, you are overloading

    From javadoc HttpServlet contains:

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    

    So you should change this:

    public void doPost(HttpServletResponse res,HttpServletRequest req)
    

    to this:

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    

    @Override annotation is not necessary but strongly recommended to avoid such mistakes.

    edited: I added override annotation like mth suggested