Sun Certified Web Component Developer/Section1/HTTP Request

HTTP Request edit

The HttpServletRequest is probably the most important interface in the whole JEE framework. It is the way the user communicates with the server. Each time the user needs something from the server, he sends a request that is converted into an HttpServletRequest object inside the Web Container.

Details edit

The first thing to notice is that HttpServletRequest extends another interface, the ServletRequest interface. This happens because the web container wasn't designed to handle only HTTP requests and responses, but all kinds of requests, using many kinds of protocols. Though, as said before, HTTP is the most common protocol used, and probably in 100% of the time you'll see only HTTPRequests in and HTTPResponses out. That is why the JEE API has a specific package named javax.servlet.http that contains all the specific classes and interfaces for the HTTP protocol.

There are many methods inside HttpServletRequest that are very handy to manipulate the user's request. You can get all kinds of information from the object the web container created for you. Some examples include:

  • HTTP headers
  • Cookies
  • Query String
  • User's IP and port
  • Form parameters
  • etc.

Parameters edit

The most common use for the HttpServletRequest object is to get the parameters sent by the user in HTML forms. Parameters are strings that the server receives from the client for specific tasks, for example: to process a query or to save or update a database record.

Parameters are sent in two ways: in HTML forms and in the query string. In both ways parameters are values identified by keys. The same key can have more then one value, meaning that the same parameter can be sent twice with two different values. Some valid examples of parameters are:

  • name=John
  • fname=John&lname=Doe&email=jdoe@gmail.com
  • query=java&lang=en
  • name=John&name=Mary&name=Josh

When sent in HTML form using the POST method, data is sent in the body of the request and can be of any size. When using GET data is restricted by the maximum size of a URL that can depend on the browser or the server, so it is not recommended to send large amounts of data using get.

Below you can see a little more detailed explanation about HTML Forms and query strings.

HTML Form edit

An HTML form is one of the ways the user can send data to the server. As was explained before HTML form can send data in two different ways: POST and GET. It is recommended to use POST if data is being sent to update something in the server, sometimes because it can be a lot of data and others because there can be confidential data that is not going to be encrypted in the URL.

To send a parameter to the server using an HTML form, just name and identify the form subelement with the name you want and get it by name in the server. A very simple example of that would be a user sending this form:

<form method="POST" action="someUrl.do">
    What is your name?<br />
    <input type="text" id="name" name="name" /><input type="submit" />
</form>

That would render something like this:

 

Then a servlet could receive the HttpServletRequest with the parameter and print back a hello message:

package org.wikibooks.scwcd;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

    public void doPost (HttpServletRequest request, 
            HttpServletResponse response) throws IOException, ServletException {
        
        String name = request.getParameter("name");
        if (name != null) {
            PrintWriter out = response.getWriter();
            out.println("Hello " + name + "!");
            out.flush();
        }
    }
}

This would result in a page showing the message "Hello [user name]!".

To see all parameters being received by the server, the following Servlet can be used:

package org.wikibooks.scwcd;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EchoParameters extends HttpServlet {

    public void doPost (HttpServletRequest request, 
            HttpServletResponse response) throws IOException, ServletException {
                PrintWriter out = response.getWriter();
		out.println("<html><body>All parameters:<ul>");
		Enumeration params = request.getParameterNames();
		String name;
		while (params.hasMoreElements()) {
			name = (String)params.nextElement();
			out.println("<li>Key : " + name + "<br />Values: <ul>");
			for (String value : request.getParameterValues(name)) {
				out.println("<li>" + value + "</li>");
			}
			out.println("</ul>");
		}
		
		out.println("</ul></body></html>");
		out.flush();
    }
}

Query String edit

The query string is a string with a specific format appended at the end of the URL. The string can be appended after a question mark sign (?) and contains key/values separated by ampersand signs (&). A simple example would be http://www.google.com/search?q=java where the query string is q=java. With that, the server receives a parameter "q" with value "java", meaning that the URL is a query into the search resource inside the google.com domain (server).

To send values in the query string just use the method GET in an HTML form as explained above.

Browsers will automatically encode the URL to correctly be interpreted by the server, because there are special symbols that cannot be sent directly, like @. Some of these symbols are used for special purposes and must not be used in keys or values in query strings, so they must be encoded, otherwise the URL will be misinterpreted by the server and the query string can be corrupted. [2] [3].

Query strings are good to save an application state: somewhere the user was or something he did that can be bookmarked for later access. But one thing to remember is that, because they can be saved, confidential data like credit card numbers must not be in the query string.

HTTP Headers edit

HTTP headers are protocol specific commands that the client (most of the times a browser) and the server uses to check what each other wants and how they are expecting to receive the answer. A very simple way to get access to a header is using the HttpServletRequest.getHeader(String) method. It will return a String that represents the value of the header received by the server for a specific header.

The following example shows how a servlet could send back as HTML all the headers received from the client:

package org.wikibooks.scwcd;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpHeadersExample extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		Enumeration names = request.getHeaderNames();
		String value = null, name = null;
		
		PrintWriter out = response.getWriter();
		
		out.println("<html><body>");
		out.println("<p>All HTTP Headers:<ul>");
		
		while (names.hasMoreElements()) {
			name = (String) names.nextElement();
			value = request.getHeader(name);
			out.println("<li><strong>" + name + "</strong>: " + value + "</li>");
		}
		out.println("</ul></p></body></html>");
		out.flush();
	}
}

That would result in the following HTML code, for a specific browser:

<html><body>
<p>All HTTP Headers:<ul>
<li><strong>host</strong>: localhost:8080</li>
<li><strong>user-agent</strong>: Mozilla/5.0 (Windows; U; Windows NT 5.1; pt-BR; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3</li>
<li><strong>accept</strong>: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8</li>
<li><strong>accept-language</strong>: en-us</li>
<li><strong>accept-encoding</strong>: gzip,deflate</li>
<li><strong>accept-charset</strong>: ISO-8859-1,utf-8;q=0.7,*;q=0.7</li>
<li><strong>keep-alive</strong>: 300</li>
<li><strong>connection</strong>: keep-alive</li>
</ul></p></body></html>

References edit

[1] - Java Enterprise Edition API - Application Programming Interface

[2] - URL Encoding

[3] - HTML URL - encoding references

[4]