Previous | Next |
One can easily use scriptlets to loop over arrays. In this example, the user is presented with choice boxes. When s/he presses the submit button, the choices are displayed.
<HTML> <BODY BGCOLOR="WHITE"> <FORM ACTION="choices.jsp"> <INPUT type="checkbox" name="music" value="Classical"> Classical<BR> <INPUT type="checkbox" name="music" value="Rock"> Rock<BR> <INPUT type="checkbox" name="music" value="Jazz"> Jazz<BR> <INPUT type="checkbox" name="music" value="Blues"> Blues<BR> <INPUT type="checkbox" name="music" value="DC-GoGo"> DC GoGo<BR> <INPUT type="submit" value="Submit"> </FORM> <% String[] selected = request.getParameterValues("music"); if (selected != null && selected.length != 0) { %> You like the following kinds of music: <UL> <% for (int i = 0; i < selected.length; i++) { out.println("<LI>" + selected[i]); } %> <UL> <% } %> </BODY> </HTML>
EXERCISE
Enter the above in a file called, choices.jsp
and run it several times.
<%! some JAVA declarations %>
You can define variables and/or methods.
Example
The following JSP page illustrates the use of a counter variable as well as a method (that sets the color of text to arandom color) using the JSP declaration construct.
<HTML> <BODY> <%! private int hitCount = 0; String randomColor() { java.util.Random random = new java.util.Random(); int R = (int) (random.nextFloat() * 255); int G = (int) (random.nextFloat() * 255); int B = (int) (random.nextFloat() * 255); return "#" + Integer.toString(R, 16) + Integer.toString(G, 16) + Integer.toString(B, 16); } %> <FONT COLOR="<%= randomColor() %>" > This page has been accessed <%= ++hitCount %> times. </FONT> </BODY> </HTML>
EXERCISE
Enter the above in a file called, declare.jsp and run it several times.
Previous | Next |
Created by Deepak Kumar (dkumar@acm.org)