Tsvetelin Pantev
Tsvetelin Pantev

Reputation: 49

Handling PATCH requests with javax.servlet.http.HttpServlet?

We are using our implementation of the javax.servlet.http.HttpServlet class as an error page(defined in the web.xml) in our Spring Web application in order to filter error information, sent to users of our API for security reasons.

As of recently we also have to handle PATCH requests to our API. As the HttpServlet was implemented with HTTP version 1.1 in mind, it does not support PATCH request("PATCH" string as a request method name). If we were to add the functionality, we have to override the whole HttpServlet implementation, which also has negative security connotations for us.

Is there an out of the box way to achieve what we are trying or do we have to switch to another implementation(also viable)?

Upvotes: 2

Views: 3698

Answers (3)

Without return, all requests will be of type PATCH and the response will be duplicate:

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String method = req.getMethod();
        if (!method.equals("PATCH")) {
            super.service(req, res);
            return; // <----- add this
        } 
        this.doPatch(req, res);
    }

Upvotes: 0

Paramjot Singh
Paramjot Singh

Reputation: 705

public class CustomServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        if (!method.equals("PATCH")) {
            super.service(req, resp);
        }

        this.doPatch(req, resp);
    }

    protected void doPatch(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("At patch method");
    }

}

Upvotes: 4

DwB
DwB

Reputation: 38290

Try overriding the HttpServlet.service method. For "DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", and "TRACE" pass the request to the super implementation of service.

For "PATCH" call a doPatch method that you define in the overriding class.

Implement doPatch in the actual class.

More info about message body:
Checkout an HTTP reference to see which methods support a method body and which do not. There is a nice table on the HTTP Wikipedia Page

Upvotes: 6

Related Questions