====== Elements of JSP (More JSP Constructs) ======
===== Scriptlets, contd. =====
==== Using Arrays ====
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.
<%
String[] selected = request.getParameterValues("music");
if (selected != null && selected.length != 0) {
%>
You like the following kinds of music:
<%
for (int i = 0; i < selected.length; i++) {
out.println("- " + selected[i]);
}
%>
==== Declarations ====
<%! 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.
<%!
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);
}
%>
This page has been accessed <%= ++hitCount %> times.
===== Summary of JSP Constructs =====
- Expressions
- Scriptlets
- Declarations
- Availability of pre-defined objects