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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<% //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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<!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>"); } %> |