Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
Converting the RegPay Applet into a Servlet

It is fairly easy to convert theRegPayloan calculating applet into a servlet. First, the servlet
must import thejavax.servletandjavax.servlet.httppackages. It must also extendHttpServlet,
notJApplet. Next, you must remove all the GUI code. Then, you must add the code that obtains
the parameters passed to the servlet by the HTML that calls the servlet. Finally, the servlet must
send the HTML that displays the results. The basic financial calculations remain the same. It is
only the way data is obtained and displayed that changes.

The RegPayS Servlet

The followingRegPaySclass is the servlet version of theRegPayapplet. As the code is
written, it assumes thatRegPayS.classwill be stored in Tomcat’s example servlets directory,
as described in Chapter 31. Remember to enter its name into theweb.xmlfile, also as
described in Chapter 31.

// A simple loan calculator servlet.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.text.*;

public class RegPayS extends HttpServlet {
double principal; // original principal
double intRate; // interest rate
double numYears; // length of loan in years

/* Number of payments per year. You could
allow this value to be set by the user. */
final int payPerYear = 12;

NumberFormat nf;

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String payStr = "";

// Create a number format.
nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);

// Get the parameters.
String amountStr = request.getParameter("amount");
String periodStr = request.getParameter("period");
String rateStr = request.getParameter("rate");

try {
if(amountStr != null && periodStr != null &&
rateStr != null) {
principal = Double.parseDouble(amountStr);

960 Part IV: Applying Java

Free download pdf