简体   繁体   中英

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");
    }
}

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM