Skip to content

Handling GET requests

The GET method is like sending a polite request to the server, saying, "Hey, can I have this webpage, please?" It's perfect for retrieving data without making any changes on the server side. This could be anything from loading a webpage to fetching specific information like search results or user profiles.

Example

Imagine you're building a simple web application that greets users with a personalized message when they visit a specific URL. Let's call it the "GreetingServlet".

java
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;

public class GreetingServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        // Set response content type
        response.setContentType("text/html");

        // Get writer object to write HTML response
        PrintWriter out = response.getWriter();

        // Write HTML response content
        out.println("<html>");
        out.println("<head><title>GreetingServlet</title></head>");
        out.println("<body>");
        out.println("<h1>Welcome to GreetingServlet!</h1>");
        out.println("<p>Hello there, visitor! Thanks for stopping by.</p>");
        out.println("</body></html>");
    }
}

In this example, we've created a Java servlet called GreetingServlet. When a GET request is made to this servlet, it responds by generating a simple HTML page with a welcoming message.

Here's a breakdown of what's happening in the code:

  • We import necessary servlet and IO packages to handle HTTP requests and responses.
  • We extend the HttpServlet class and override the doGet method, which gets called when the servlet receives a GET request.
  • Inside the doGet method, we set the content type of the response to text/html since we're going to send back an HTML page.
  • We obtain a PrintWriter object from the HttpServletResponse object, which allows us to write the HTML response.
  • Then, we simply write the HTML content using the PrintWriter, including a basic welcome message.

To use this servlet, you would compile it into a .class file and deploy it on a servlet container like Apache Tomcat. Once deployed, you can access the servlet by visiting its URL, and it will respond with the greeting message.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.