docs:programming:jsp:elements_of_jsp_more_jsp_constructs

Elements of JSP (More JSP Constructs)

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>
		<%! 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>
  1. Expressions
  2. Scriptlets
  3. Declarations
  4. Availability of pre-defined objects
  • docs/programming/jsp/elements_of_jsp_more_jsp_constructs.txt
  • Last modified: 2008/08/03 00:25
  • by 127.0.0.1