Java MCQ: Which method is used to handle POST requests in a Servlet?
a) doPost()
b) doGet()
c) service()
d) init()
Answer:
a) doPost()
Explanation:
The doPost()
method is used to handle POST requests in a Servlet. When a client sends a POST request, typically from an HTML form submission, the doPost()
method of the associated Servlet is invoked to process the request and generate a response.
Here’s an example of a doPost()
method in a Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Welcome, " + username + "</h1>");
}
In this example, the doPost()
method processes form data sent by the client and sends a personalized response.
The doPost()
method is commonly used for handling form submissions, uploading files, and other actions that require the client to send data to the server.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html