Sending XMLHttpRequest

I’ll start at the beginning: creating an XMLHttpRequest and sending it from the browser. Unfortunately, the method of creating an XMLHttpRequest varies from browser to browser. The function in the JavaScript in Listing 2 mitigates these difficulties for different browsers by determining the correct approach for a given browser and returning the XMLHttpRequest ready for use. It’s best to think of it as boilerplate code: simply copying it into your JavaScript library and using it when you need XMLHttpRequest.

The onclick statement called addToCart() is responsible for updating the state of the cart in the Ajax call. The first thing addToCart() needs to do is get the XMLHttpRequest data by calling newXMLHttpRequest(). Next, it registers a callback function to get the server’s response.

Since the request will change state on the server, I will use the HTTP POST method to do this. Sending data via POST is done in three steps. First, I need to open a connection to the server source I’m connecting to, which in this case is the servlet listed in the cart.do page. Next, I set a header in the XMLHttpRequest saying that the content of the request is encoded data. Finally, I send the request with the encoded data in the body of the content.

After all this, you understand the first part in the Ajax mechanism – the actual creation and transmission of the HTTP request from the client. The next step is to code a servlet in Java to handle the request.

Servlet request processing
Handling XMLHttpRequest with a servlet is the same as handling an ordinary HTTP request from the browser. The encoded data sent in the POST request content can be retrieved through calls to HttpServletRequest.getParameter(). Ajax requests participation in an HttpSession, the same as in regular Web requests from the application. This is useful for the example shopping cart scenario because it allows me to encapsulate the state of the custom shopping cart in JavaBeans and hold that state during the session between the two requests.

Part of a simple servlet that handles Ajax requests to update the buyer’s cart. The Cart is retrieved from the user’s session and its state is updated according to the query parameters. The Cart is then serialized in XML format and the XML is generated in ServletResponse. It is important to set the content type of the request to application/xml, otherwise XMLHttpRequest will not parse the content of the response.