/**
* Copyright (c) 2002 by Phil Hanna
* All rights reserved.
*
* You may study, use, modify, and distribute this
* software for any purpose provided that this
* copyright notice appears in all copies.
*
* This software is provided without warranty
* either expressed or implied.
*/
import java.text.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
/**
* Numeric format used to display temperatures
*/
private static final DecimalFormat FMT
= new DecimalFormat("#0.00");
/**
* Factor to convert from km/l to mi/gal
*/
private static final double CONVERSION_FACTOR = 2.352145;
/**
* Handles a GET request
*/
public void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set up for creating HTML output
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Generate heading
out.println
( "<html>"
+ "<head>"
+ "<title>Fuel Efficiency Conversion Chart</title>"
+ "</head>"
+ "<body>"
+ "<center>"
+ "<h1>Fuel Efficiency Conversion Chart</h1>"
+ "<table border='1' cellpadding='3' cellspacing='0'>"
+ "<tr>"
+ "<TH>Kilometers per Liter</th>"
+ "<TH>Miles per Gallon</th>"
+ "</tr>"
);
// Generate table
for (double kmpl = 5; kmpl <= 20; kmpl += 1.0) {
double mpg = kmpl * CONVERSION_FACTOR;
out.println
( "<tr>"
+ "<td align='right'>" + FMT.format(kmpl) + "</td>"
+ "<td align='right'>" + FMT.format(mpg) + "</td>"
+ "</tr>"
);
}
// Generate footer
out.println
( "</table>"
+ "</center>"
+ "</body>"
+ "</html>"
);
}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<context-param>
<param-name>name</param-name>
<param-value>John</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>password</param-value>
</context-param>
<servlet><servlet-name>MyServletName</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>MyServletName</servlet-name>
<url-pattern>/index.html</url-pattern>
</servlet-mapping>
</web-app>
Download: ServletConverterKilometersMiles.zip( 89 k)