The intention is to introduce the communication in between the servlet and JSP. The welcome page is designed by the HTML code.
<html>
<title>Srv-Jsp Communication</title>
<form action=”a.jsp”>
<body>
<center><font color=”black” size=”8″>Enter A Number:</font>
<input type=’text’size=’50’ name=”t1″><br><br>
<input type=’submit’ value=’submit’ name=”b1″ />
<input type=’reset’ value=’reset’ name=’b2’/>
</center>
</body>
</form>
</html>
Output:
“a.jsp”
<html>
<%
try
{
int no=Integer.parseInt(request.getParameter(“t1”));
int res=no*no;
if(res>=100)
{
out.println(“<center><font color=’red’ size=’8′>”);
out.println(“Square of The Number is=”+res);
out.println(“</font></center>”);
}
else
{
out.println(“<br><br><center><font color=’red’ size=’6′>Your selection Does
not Vary The Condition..”);
}
}
catch(Exception e)
{
System.out.println(e);
}
%>
</html>
Output:
Explanation of the above program
The aim of this program is to find out the square of the number if the result is greater than 100, then it goes to the JSP program, otherwise it goes to servlet program.
As the JSP program communicates, with the servlet program, the URL pattern of the servlet program is passed into the form action.
• int no=Integer.parseInt(request.getParameter(“tl”));
The number which is passed that is read by the getParameter() and assign in the no variable of int type.
• int res=no*no;
The square of the number is calculated and assigned to the res variable of int type.
• if(res>=100)
{
out.println(“<center><font color=’red’ size=’8′>”) ;
out.println(“Square Of The Number Is=”+res);
out.println(“</font></center>”) ;
}
If the result requested is greater than 100, then it calculates the square of the number.
• else
{
RequestDispatcher=request.getRequestDispatcher{“/Srv·);
rd.forward(request,response);
}
If the result is less than 100,we pass the request then through the RequestDispatcher object to the servlet program, where the cube of the number is calculated.
• catch(Exception e)
{
System.out.println(e) ;
}
The exception is handled by the catch block.
The square of the number 25 is 625 and it is greater than 100, so the request goes to the SP page and processing is done.
But if the square of the number is greater than or less than 100, then the request goes to the servlet program and calculates the cube of the number.
This time we pass the number 2 and the square of the number is 4 and it is less than 100, so the request goes to the Servlet program through the RequestDispatcher object that’s why we pass the URL pattern of the servlet program in RequestDispatch method.