We will now create a non-trivial Java web application which will require the use of a servlet.
First of all, let’s create a simple HTML page containing a form to allow the user to choose a type of conversion (Rupees to Dollars / Dollars to Rupees) and the amount to convert. At this point, clicking on Go! makes no sense (but try it!)
The second step is to add a servlet to the web application which will handle the conversion. The servlet will be called with two parameters, the type of conversion and the amount, through the HTTP GET (or POST) request. [NB: We will have to add the servlet-api.jar to the web application WEB-INF/lib folder. Get the jar from Tomcat.]
The servlet will then have to get the parameters from the request, validate them and calculate a new amount based on some hard-coded conversion rate (e.g. 1 Dollar is 30 Rupees). This value should then be sent back to the browser (in an HTTP response) for display.
Export the WAR file and examine its contents. Can you see the Java servlet in it? Is it in source code form or in compiled form?
Enhancing the application
As it is, the web application uses a hard-coded conversion rate and this is artificial as, in real life, this rate changes daily. Update the web application to retrieve the conversion rate from a web service.
To make things simple, we are going to assume that the exchange rate is available at an URL similar to www.server.com/exchangerate.txt (see, web services can be simple!) And, because we are dealing with resources which are accessed through a URL, use a Java URL object during the implementation.