Table of Contents

Elements of JSP

How it works

Whenever a .jsp is requested for the first time, the server does the following:

  1. Translates the .jsp page into a servlet
  2. Compiles the servlet into a class file
  3. Executes the servlet (response is sent to the client)

Subsequent requests (as long as the .jsp page is unchanged) use the same loaded class file.

Anatomy of a JSP Page

A JSP page is a mixture of standard HTML tags, web page content, and some dynamic content that is specified using JSP constructs. Everything except the JSP constructs is called Template Text.

JSP Constructs

JSP Comments: Different from HTML comments

		<!-- an HTML comment -->
		<%-- a JSP comment --%>

JSP comments are used for documenting JSP code and are not visible client-side (using browser's View Source option) where as HTML comments are visible.

(JAVA) Expressions

		<%= some_java_expression %>

Example:

<%= new java.util.Date().toString() %>

Output of the expression is placed in the HTML template at the same location.

There are some pre-defined Java variables/objects available for use in expressions (provide access to important servlet functionality):

request This is the same object as HttpServletRequest parameter in th get/post methods. Same methods (like, getParameter, getAttribute, etc) can be applied to it.

Example:

   <HTML>
    <HEAD>
     <TITLE>JSP Expressions: Predefined Objects</TITLE>
    </HEAD>
    <BODY>
     <H1>Using Predefined Objects</H1>
     <UL>
      <LI> Your Hostname: <%= request.getRemoteHost() %>
      <LI> Your Session ID: <%= session.getId() %>
      <LI> The value of INFO parameter: <%= request.getParameter("INFO") %>
    </BODY>
   </HTML>

Scriptlets

Scriptlets are arbitrary pieces of Java code inserted in the page using the format:

		<% some_java_code %>

Example 1

   <HTML>
    <HEAD>
     <TITLE>JSP: Scriptlets</TITLE>
    </HEAD>
     <%
        String bgColor = request.getParameter("COLOR");
       
        if (bgColor == null)
           bgColor = "WHITE";
        
     %>
    <BODY BGCOLOR="<%= bgColor %>" >
     <H1>Example Scriptlet: Sets background color</H1>
       
    </BODY>
   </HTML>

Example 2

   <HTML>
    <HEAD>
     <TITLE>JSP: Scriptlets 2</TITLE>
    </HEAD>
     <% String bgColor = request.getParameter("COLOR"); %>
       
     <% if (bgColor == null) { %>
           <BODY BGCOLOR="FFFFFF" >
     <% } else { %>
           <BODY BGCOLOR="<%= bgColor %>" >
     <% } %>
       
     <H1>Example Scriptlet: Conditionally sets background color</H1>
     <% if (bgColor == null) { %>
           You did not supply a color, I used white.
     <% } else { %>
           Here is the color you requested.
     <% } %>
       
    </BODY>
   </HTML>