Handle HTTP PATCH request with Java Servlet image 44

Handle HTTP PATCH request with Java Servlet

The Java Servlet specification does not include handling a PATCH request. That means that class  javax.servlet.http.HttpServlet does not have a doPatch() method, unlike doGet, doPost, doPut etc.

That does not mean that a Java Servlet can not handle PATCH requests. It is quite simple to make it do that.

The trick is overriding the service(request,response) method – and have it respond to PATCH requests (in a special way) and to all other requests in the normal way. Or to do it one step more elegantly:

  1. create an abstract class – MyServlet for example – that extends from HttpServlet, override servce() and add an abstract doPatch() method – that is not supposed to be ever invoked but only be overridden
    package nl.amis.patch.view;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public abstract class MyServlet extends HttpServlet {
    
        public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            if (request.getMethod().equalsIgnoreCase("PATCH")){
               doPatch(request, response);
            } else {
                super.service(request, response);
            }
        }
        
        public abstract void doPatch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
    
    }
    
    
  2. any servlet (class) that should handle PATCH requests should extend from this class [MyServlet] and implement the doPatch() method

 

package nl.amis.patch.view;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(name = "TheServlet", urlPatterns = { "/theservlet" })
public class TheServlet extends MyServlet {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doPatch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>TheServlet</title></head>");
        out.println("<body>");
        out.println("<p>The Servlet has received a PATCH request and will do something meaningful with it! This is the reply.</p>");
        out.println("</body></html>");
        out.close();
    }
}

 

Here is the result of sending a PATCH request from Postman to the Servlet:

 

image