Quick Take
Older Java Servlet APIs do not provide a dedicated doPatch() callback like doGet() or doPost(). This tutorial shows how to process an HTTP PATCH request by overriding HttpServlet.service() and dispatching PATCH requests to a custom method while leaving other verbs to the superclass. The code uses the historical javax.servlet namespace. For modern applications, check the Servlet or Jakarta Servlet version and your framework’s supported method dispatch before adopting this pattern.
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:
- 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; } - 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:
