Monday, June 9, 2008

Simple JSP Tutorial

This jsp accepts a number from an html form and prints squareroot of that number on the same page. Paste this code to file "first.jsp" and move it to tomcat's webapps/ROOT directory. Start tomcat and browse to localhost:8080/first.jsp. We put java code in <% %> block , other parts are standart html. <%=variable %> prints variable into html code just like <%out.print(variable);%> does.

request , response and out objects are standart JSP objects that can be used to access http request and response.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample JSP</title>
</head>
<body>
<%
String strNumber= request.getParameter("number");
double mySqrt = 0.0;
if ( strNumber == null )
strNumber = "";
else {
double dNumber = Double.parseDouble(strNumber);
mySqrt = Math.sqrt(dNumber);
}
%>

<form action="first.jsp" method="post">
Enter Number: <input type="text" name="number" value="<%=strNumber%>">
<input type="submit">
<br><br>
The Sqrt is <%out.print(mySqrt);%>
</body>
</html>

No comments: