MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

What do Servlets do?

Servlets replace how a Web server responds to a request for some resource. In this way they are invisible to someone visiting a Web application using a browser: the browser makes standard requests for standard Web resources, the addresses of which usually look like ordinary Web pages. The server, on the other hand, will realise that a specific address is for a Servlet in a given Web application. It will then pass control to the Servlet to handle the whole request. Any data sent to the server with the request is past to the Servlet, and the Servlet may return any data it wishes (including HTML) to the Web browser.

Because Servlets replace a portion of a Web server's functionality, we need to know a bit about HTTP, the HyperText Transfer Protocol used by Web servers and Web browsers to communicate with each other.

Request Methods

When a Web browser requests a Web page, that request is made using HTTP. Now, HTTP defines a number of actions that can be taken on a Web page. These actions are called request methods. The two that are of interest to you in this chapter are GET and POST requests. Both requests are used when data (for instance, an HTML file) is being requested from a Web server. A GET request, in particular, is used only for requesting data, although it does have some ability to pass data to a Web server as well. POST requests also request data, but importantly, data is meant to be sent to the Web server as well, and this data is meant to be processed. A POST request may result in a Web application changing its state (as it processes the data). A GET request should never change the state of a Web application. Indeed, GET is defined by HTTP to be a Safe Method, which are request methods that never modify the state of the Web application.

When an HTML file is requested by a Web browser, this request is by default made as a GET request. The important exception to this is with HTML forms, which can request that the data be sent using a POST request (by setting the method attribute of the form tag to “POST”). The Web page set as the form's action will then be requested using a POST request.

When you are writing your own Servlets, you will have the chance to directly make use of, and implement, GET and POST requests. You will notice little difference between them apart from how they transfer data from the Web browser to the Web server: a GET request will always display the sent data in the URL, while a POST request will generally never do this. Apart from this, you must always remember to use the two request types only where they are intended. Specifically, it is incorrect to update the Web server's state using a GET request.