Handling HTTP GET Requests in Java Servlets

Earlier, we’ve introduced you to Java Servlets — what they are, life cycle, advantages. Let’s move ahead with Java Servlets and get some simple code to handle the HTTP GET Request to show you how to write a servlet.

Servlets can be used for handling both the GET Requests and the POST Requests. However in this post, let’s write the code for handling the GET Request. The HttpServlet class is used for handling HTTP GET Requests as it has some specialized methods that can efficiently handle the HTTP requests. These methods are;

  • doGet()
  • doPost()
  • doPut()
  • doDelete()
  • doOptions()
  • doTrace()
  • doHead()

An individual developing servlets for handling HTTP Requests needs to override one of these methods in order to process the request and generate a response. The servlet is invoked dynamically when an end-user submits a form.

Let’s look at a sample HTML FORM

Here’s the code for ColServlet.java that overrides the doGet() method to retrieve data from the HTTP Request and it then generates a response as well.

In order to make this code work, compile the servlet and open the HTML file and hit the “submit” button after selecting a color. Once you press the submit button, the browser will display a response that is generate dynamically by invoking the servlet. Well, this was a very simple servlet and it’s always good to start with basic stuff. However, there’s no end to what you can do with Java Servlets as you can make complex servlets to do several complex tasks.

  • http://www.venukb.com Venu

    I'm not sure if compiling the servlet is enough to get going !
    Don't you need to run it on a servlet container?

  • http://www.venukb.com Venu

    I'm not sure if compiling the servlet is enough to get going !
    Don't you need to run it on a servlet container?

  • sakthi

    where is another exaples for doPost .................etc

  • Pingback: Can PHP make HTTP Get request to Java? | BlogoSfera()