Scriptlets

To add Java code to a JSP, simply add a scriptlet. Scriptlets are Java code snippets in a JSP surrounded by <% and
%> or <jsp:scriptlet> </jsp:scriptlet>. A simple example of a scriptlet (actually 2 scriptlets) would introduce a loop
to the hello.jsp example.


<html>
 <body>
     <%
     for (int i =0; i < 10; i++) {
     %>
     <h1>Hello, JSP World</h1>
     <%
     }
     %>
 </body>
</html>




























Recall that the source code is written for you by the container. Each container may produce slightly different source
code, but they all provide the same functionality. You may hear the portion of the container that creates a servlet
from a JSP referred to as the JSP Compiler or JSP Engine.

By looking at the source code below for this hello.jsp file you can see how scriptlets are mixed with HTML code.
All HTML and scriptlets go into a _jspService() method.  The _jspService method is called for all HTTP methods
(GET, POST, etc.). Notice the two objects passed to the _jspService() method: HttpServletRequest and
HttpServletResponse objects. The _jspService() method acts just like the HTTP servlet’s service() method. All
HTML code is nested in out.write() statements so they can be mixed with Java. The scriptlet code is taken out
verbatim and placed in the _jspService() method relative to the position of the HTML out.write statements.
Portions of the code have been removed for brevity.


package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class hello_jsp extends org.apache.jasper.runtime.HttpJspBase
 implements org.apache.jasper.runtime.JspSourceDependent {
//portion removed for brevity

public void _jspService(HttpServletRequest request, HttpServletResponse
response)
     throws java.io.IOException, ServletException {

 //Portion removed for brevity

 try {
   //Portion removed for brevity
   out = pageContext.getOut();
   _jspx_out = out;
  
 out.write("<html>\n");
   out.write("    <body>\n");
   out.write("        ");

     for (int i =0; i < 10; i++) {
   out.write("\n");
   out.write("        <h1>Hello, JSP World</h1>\n");
   out.write("        ");
     }
    
   out.write("\n");
   out.write("    </body>\n");
   out.write("</html>\n");
 } catch (Throwable t) {
   if (!(t instanceof SkipPageException)){
     out = _jspx_out;
     if (out != null && out.getBufferSize() != 0)
       out.clearBuffer();
     if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
   }
 } finally {
   if (_jspxFactory != null) _jspxFactory.releasePageContext
(_jspx_page_context);
 }
}
}
Scriplets
Table of Contents
Courseware
Training Resources
Tutorials
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Services