jcubic
jcubic

Reputation: 66480

Java Servlet return error 405 (Method Not Allowed) for POST request

My servet work fine for get requests but when I call POST (using jquery ajax $.post) I get error 405 (Method Not Allowed)

Here is my code:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class init extends HttpServlet {
    public init() { }
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("GET");
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalStateException {
        response.setContentType("application/json");
        ServletInputStream in = request.getInputStream();
        PrintWriter out = response.getWriter();
        out.print("POST");
    }
}

Upvotes: 6

Views: 19874

Answers (2)

Sahan Maldeniya
Sahan Maldeniya

Reputation: 1046

This happened to me when my method call

"super.doGet(req, resp)" or "super.doPost(req, resp)" .

After i removed above super class calling from the doGet and doPost it worked fine.

Infact those super class calling codes were inserted by the Eclipse IDE template.

Upvotes: 16

Andreas Aumayr
Andreas Aumayr

Reputation: 1006

Are you sure that you actually override the doPost Method?

The signature looks like this:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, java.io.IOException

but you specify it like this:

public void doPost(HttpServletRequest request, HttpServletResponse response) 
           throws ServletException, IOException, IllegalStateException

I am not sure whether this is allowed: Overriding Java interfaces with new checked exceptions

Try the following steps:

  1. Add the @Override Annotation
  2. Remove the throws IllegalStateException (shouldn't be a problem as it is a runtime exception)

Upvotes: 12

Related Questions