This post teaches you how to write a program to find Celsius from Fahrenheit using JSP web application. You already know JSP is a web application which is slightly different from the traditional Java programming.
In this program I have not used JSP and Servlet but only JSP code embedded in the HTML page, basically Single page web application.
Let’s write JSP code to convert Fahrenheit to Celsius:
<%
//check if post request
if("POST".equalsIgnoreCase(request.getMethod()))
{
//define variables
float fahrenheit, celsius;
//get the value from text box and convert into float
fahrenheit = Float.parseFloat(request.getParameter("name"));
//apply the formula
celsius = (fahrenheit - 32) * 5/9;
//print the value
out.print("<h3>Celsius: "+celsius+"</h3>");
}
%>The above JSP script gets the value from Text box named as “fahrenheit” and then converts into Celsius by using the below formula:
celsius = (fahrenheit – 32) * 5/9;
Here is the entire JSP code embedded with HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Convert Fahrenheit to Celsius JSP Program - Tutorialsmade.com</title>
</head>
<body>
<h2>Convert Fahrenheit to Celsius in JSP - Tutorialsmade.com!</h2>
<form action="" method="post">
<label>Enter Fahrenheit: </label><input type="text" name="fahrenheit" />
</form>
</body>
</html>
<%
//check if post request
if("POST".equalsIgnoreCase(request.getMethod()))
{
//define variables
float fahrenheit, celsius;
//get the value from text box and convert into float
fahrenheit = Float.parseFloat(request.getParameter("fahrenheit"));
//apply the formula
celsius = (fahrenheit - 32) * 5/9;
//print the value
out.print("<h3>Celsius: "+celsius+"</h3>");
}
%>