Basic Servlet
A basic Java servlet program that demonstrates handling GET, POST, PUT, and DELETE requests with examples for each HTTP method. You'll need a Java Servlet container like Apache Tomcat to run this code.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CRUDServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Handling GET request
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("Handling GET request");
}
// Handling POST request
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("Handling POST request");
}
// Handling PUT request
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("Handling PUT request");
}
// Handling DELETE request
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("Handling DELETE request");
}
}
This servlet defines four methods to handle each of the HTTP methods (GET, POST, PUT, DELETE).
Here are examples of how to use these HTTP methods:
GET Request:
Open a web browser and navigate to http://your-server/context-root/example (replace "your-server" and "context-root" with the appropriate values).
You'll see "Handling GET request" displayed in the browser.
POST Request:
You can use a tool like
curl
to send a POST request from the command line:curl -X POST http://your-server/context-root/example
You'll see "Handling POST request" displayed in the response.
PUT Request:
You can use
curl
to send a PUT request from the command line:curl -X PUT http://your-server/context-root/example
You'll see "Handling PUT request" displayed in the response.
DELETE Request:
You can use
curl
to send a DELETE request from the command line:curl -X DELETE http://your-server/context-root/example
You'll see "Handling DELETE request" displayed in the response.
Remember to replace "your-server" and "context-root" with the appropriate values based on your server configuration.
Last updated
Was this helpful?