Converting the RegPay Applet into a Ser vlet
It is fairly easy to convert the RegPay loan calculating applet into a servlet. First, the servlet
must import the javax.servlet and javax.servlet.http packages. It must also extend HttpServlet,
not JApplet. 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 Ser vlet
The following RegPayS class is the servlet version of the RegPay applet. As the code is
written, it assumes that RegPayS.class will be stored in Tomcat's example servlets directory,
as described in Chapter 31. Remember to enter its name into the web.xml file, 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);
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home