Java MCQ: Which method is used to handle GET requests in a Servlet?
a) doPost()
b) doGet()
c) service()
d) init()
Answer:
b) doGet()
Explanation:
The doGet()
method is used to handle GET requests in a Servlet. When a client sends a GET request to a web server, the doGet()
method of the associated Servlet is invoked to process the request and generate an appropriate response.
Here’s an example of a doGet()
method in a Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello, World!</h1>");
}
In this example, the doGet()
method sends an HTML response to the client with a simple “Hello, World!” message.
The doGet()
method is essential for handling requests where the client wants to retrieve data from the server, such as loading a web page or submitting a form via a GET request.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html