Processing GET and POST requests in CGI with Java

On the client side, the form submission method (GET or POST) is specified in the attribute method of the form element.

Form that uses the GET method

<form method="get" action="...">

Enter your name:

Form that uses the POST method

<form method="post" action="...">

Enter your name:


On the server side, the difference between the processing of the GET request and the POST request is that in the first case the parameters string is set as an environmental variable QUERY_STRING, while in the second case the parameter string is put on the standard input stream. In our example, both methods are handled by the BASH shell script runjava

#!/bin/bash
read a
echo -n $a | java Methods

This script invokes the following Java code

import java.util.Scanner;

public class Methods
{
  public static void main(String[] args)
  {
    String param_str = System.getenv("QUERY_STRING");  // attempt to get 
    String method = "GET";                             //   params with GET

    if (param_str == null || param_str.length() < 2)   // get params with POST
    {
      Scanner input = new Scanner(System.in);          // reading the standard
      param_str = input.next();                        // input stream
      method = "POST";
    }
                                                       // shorten the string
    param_str = param_str.substring(0, Math.min(param_str.length(), 100));

    Scanner tokens = new Scanner(param_str);           // tokenize the data
    tokens.useDelimiter("=");
    String name = tokens.next();                       // get parameter name
    String value = tokens.next();                      // get parameter value 

    System.out.printf("Content-Type: text/html\n\n");  // compose HTML 
    System.out.printf("<p>Response from Java</p>");
    System.out.printf("<html><head><title></title></head><body>");
    System.out.printf("Method: %s <br>", method);
    System.out.printf("Parameter string: %s <br>", param_str);
    System.out.printf("Parameter name: %s <br>", name);
    System.out.printf("Parameter value: %s <br>", value);
    System.out.printf("</body></html>");
  }
}

Note that this simple script does not accept parameter strings exceeding 100 characters and does not do URI decoding.