JSP Programs
JSP Programs
1. The following JSP program calculates factorial values for an integer number, while
the input is taken from an HTML form.
Input.html
<html>
<body>
<form action="Factorial.jsp">
Enter a value for n: <input type="text" name="val">
<input type="submit" value="Submit">
</form>
</body>
</html>
Factorial.jsp
<html>
<body>
<%!
long n, result;
String str;
long fact(long n) {
if(n==0)
return 1;
else
return n*fact(n-1);
}
%>
<%
str = request.getParameter("val");
n = Long.parseLong(str);
result = fact(n);
%>
<b>Factorial value: </b> <%= result %>
</body>
</html>
2. The following JSP program shows the Fibonacci series up to a particular term, while the
input is taken from an HTML form.
Input.html
<html>
<body>
<form action="Fibonacci.jsp">
Enter a value for n: <input type="text" name="val">
<input type="submit" value="Submit">
</form>
</body>
</html>
Fibonacci.jsp
<html>
<body>
<%!
int n;
String str;
int fibo(int n) {
if(n<2)
return n;
else
return fibo(n-1) + fibo(n-2);
}
%>
<b>Fibonacci series: </b><br>
<%
str = request.getParameter("val");
n = Integer.parseInt(str);
Date.jsp
<html>
<body>
<%-- JSP comments --%>
<%@page import="java.util.Date"%>
<%!
Date date;
%>
<%
date = new Date();
%>
<b>System date and time: </b> <%= date %>
</body>
</html>
Powerof2.jsp
<html>
<head>
<title>Powers of 2</title>
</head>
<body>
<center>
<table border="2" align="center">
<th>Exponent</th>
<th>2^Exponent</th>
<% for (int i=0; i<=10; i++) { //start for loop %>
<tr>
<td><%= i%></td>
<td><%= Math.pow(2, i) %></td>
</tr>
<% } //end for loop %>
</table>
</center>
</body>
</html>