====== Elements of JSP ======
===== How it works =====
Whenever a .jsp is requested for the first time, the server does the following:
- Translates the .jsp page into a servlet
- Compiles the servlet into a class file
- 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 ====
<%-- 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.
* **out**
* The servlet printwriter.
* **session**
* Same as servlet session object.
Example:
JSP Expressions: Predefined Objects
Using Predefined Objects
- Your Hostname: <%= request.getRemoteHost() %>
- Your Session ID: <%= session.getId() %>
- The value of INFO parameter: <%= request.getParameter("INFO") %>
==== Scriptlets ====
Scriptlets are arbitrary pieces of Java code inserted in the page using the format:
<% some_java_code %>
Example 1
JSP: Scriptlets
<%
String bgColor = request.getParameter("COLOR");
if (bgColor == null)
bgColor = "WHITE";
%>
Example Scriptlet: Sets background color
Example 2
JSP: Scriptlets 2
<% String bgColor = request.getParameter("COLOR"); %>
<% if (bgColor == null) { %>
<% } else { %>
<% } %>
Example Scriptlet: Conditionally sets background color
<% if (bgColor == null) { %>
You did not supply a color, I used white.
<% } else { %>
Here is the color you requested.
<% } %>