How to use 'if' statement in jsp page?
This is detailed java code that shows how to use 'if' statement in jsp page. This statement is used to test conditions. You can understand use of this statement by a real world example. Suppose a person takes hand out the window to test if it's raining and will take decision according to the test result. If it is raining then the person takes an umbrella. If it isn't raining then don't.
Create a new directory named "user" in the tomcat-6.0.16/webapps and paste WEB-INF directory in same.
use_if_statement.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>use of 'if' statement through jsp</TITLE> </HEAD> <BODY bgcolor="#6E6E6E"> <FORM NAME="form1" ACTION="use_if_statement.jsp" METHOD="get"> <table bgcolor="#D8D8D8"> <font color="#F8E0F7">Enter integer number here.</font> <tr> <td> Enter number </td> <td><input type="text" name="num"></td> </tr> <tr align="center"><td></td> <td><INPUT TYPE="submit" VALUE="show range"></td> </table><br> <table bgcolor="#F6E3CE" border="1" width="23%"> <% // here if statement will check that text box is null or empty if (request.getParameter("num") != null && request.getParameter("num") != "") { // change string value of text box to a long type long num = Long.parseLong(request.getParameter("num")); /* here 'if' will make decision according to some conditions given below. */ if (num >= 0 && num <= 5) { %> <tr align="center"> <td><Font>You have entered number in range 0 and 5.</font></td> </tr> <% } if (num >= 6 && num <= 10) { %> <tr align="center"> <td><Font>You have entered number in range 6 and 10.</font></td> </tr> <% } if (num > 10) { %> <tr align="center"> <td><Font>You have entered number greater than 10.</font></td> </tr> <% } } %> </table> </FORM> </body> </html> |
Save this code as a .jsp file named "use_if_statement.jsp" in the directory Tomcat-6.0.16/webapps/user/ and you can run this jsp page with url "http://localhost:8080/user/use_if_statement.jsp" in address bar of the browser.
When user enters integer value in appropriate text box and click on show range button. For this example suppose user enters value 3.
When user enter value greater than 10 in text box and click square button.