Abbey Workshop

JSP: Enumeration Scriptlet

Scriptlets are pieces of Java code embedded in a an HTML page. The example below shows an example scriptlet. You can see that the Java code is enclosed in a JSP tags <% and %>. The example uses the Enumeration object to get the HTTP headers passed to the server, then displays each header and the data associated with that header. In addition, this example also use some of the implicit objects available in any JSP page. In this case, the out object and the request object.

Note that each line is a complete Java statement. Statements must end in semicolons, and blocks must begin and end in { } as you normally would use them in a Java program. Notice the while loop is written just like it would be for a Java program, servlet or applet.

Source for enumScriptlet.jsp

   1:<html>
   2:<head>
   3:<title>Enumeration Scriplet</title>
   4:</head>
   5:<body>
   6:<h2>Enumerations</h2>
   7:<p></p>
   8:<p></p>
   9:<h2>Enumerate through HTTP Header</h2>
  10:<h4>HTTP Header (Not in order)</h4>
  11:<p>
  12:<% 
  13:java.util.Enumeration e = request.getHeaderNames();
  14:  while (e.hasMoreElements()){ 
  15:      String name = (String) e.nextElement();
  16:      out.print("<b>" + name + ": </b>"); 
  17:        out.print(request.getHeader(name) + "<br>");
  18:    } 
  19:%>
  20:</p>
  21:</body>
  22:</html>

Scriptlets can be very complicated or very simple. For example to display some text you could create a scriptlet like this.

<%  out.print("Here is a line of text."); %>

This scriptlet is just one line of Java code.

When to Use

Scriptlets are best used when you do need multiple lines of Java code to perform a specific task. If you are just printing out text, it's easier to use JSP Expressions.