The following code example demonstrates a Program to Create a JSP Method that Accepts a Number and Returns its Double.
Here is an example of a JSP program that creates a method to double a number.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Double Calculator</title>
</head>
<body>
<h2>Double Calculator</h2>
<form action="DoubleCalculator.jsp" method="post">
Enter a number: <input type="text" name="number"> <br> <br>
<input type="submit" value="Submit">
</form>
<%
int number = Integer.parseInt(request.getParameter("number"));
int result = doubleNumber(number);
out.println("<br><br>The double of the number is: " + result);
%>
<%!
public int doubleNumber(int number) {
return number * 2;
}
%>
</body>
</html>
In this program, we first create a form with an input field for the user to enter a number. The form submits the number to the same JSP page using the post
method. When the form is submitted, the JSP page retrieves the number using request.getParameter("number")
and converts it to an integer using Integer.parseInt()
.
Next, we call the doubleNumber()
method and pass the number to it. The method is defined within the JSP page using the <%!
and %>
tags. The method takes a single integer argument and returns its double.
Finally, we use out.println()
to print the result of doubling the number.