Wednesday, April 27, 2011

JSP: scriptlets

Scriptlets
Scriptlets provide a method for directly inserting bits of Java code between
chunks of template text. A scriptlet is defined with a start ,<%, an end, %>, with
code between. Using Java, the script is identical to normal Java code but without
needing a class declaration or any methods. Scriptlets are great for providing low-
level functionality such as iteration, loops, and conditional statements, but they
also provide a method for embedding complex chunks of code within a JSP.
For many reasons complex scriptlets should be avoided. This is mainly due to
the fact that the more scriptlets are used the harder it is to understand and
maintain a JSP. In this chapter most of the scriptlet examples are purposely kept
simple. This aids in directly demonstrating the core functionality of JSP, but it is
also done so that examples do not appear to encourage heavy use of scriptlets. As
an introduction, Listing 2 provides a simple JSP that loops to produce multiple
lines of text. Looping is accomplished the same as in Java but by placing the
equivalent Java code inside scriptlet elements. Loop.jsp
Listing 2 
<html>
<head>
<title>Loop Example</title>
</head>
<body>
<% for (int i=0; i<5;i++) { %>
Repeated 5 Times.<br>
<% } %>
</body>
</html>
Save  Loop.jsp in the base directory of the jspbook Web Application and
browse to http://127.0.0.1/jspbook/Loop.jsp. The page shows up with the
statement, “Repeated 5 Times.”, repeated five times.

output
Repeated 5 Times
Repeated 5 Times
Repeated 5 Times
Repeated 5 Times
Repeated 5 Times


It is important to note that the contents of the scriptlet did not get sent to a
client. Only the results of the scriptlet did. This is important because it shows that
scriptlets are interpreted by a container and that code inside a scriptlet is not by
default shared with visitors of the JSP.
A JSP may contain as many scriptlets as are needed, but caution should be
taken not to overuse scriptlets. Scriptlets make a JSP very hard to maintain and
are not easily documented; for example, tools like javadoc do not work with JSP

JSP Syntax and Semantics


JSP is not governed by the syntax and semantics defined by the Java 2 specifica-
tions. Translated JSP source code is just Java,but when you author a JSP, you abide
instead by the rules laid out in the JSP specification. With each release of the JSP
specification, these rules grow, and they cannot be easily summed by a few sen-
tences. The majority of this chapter focuses on explaining the current syntax and
semantics of JSP. Much of the functionality found in JSP is taken directly from the
underlying Servlet API .
Everything in a JSP is broken down into two generic categories called elements
and template data. Elements are dynamic portions of a JSP. Template data are the
static bits of text between. Template data are easily categorized as they are all the
text arbitrarily placed on a JSP and meant to be directly sent to a client. Elements
are easily categorized as custom actions, tags, and the content allowed to be in
between as defined by the JSP specifications.
The concept of elements and template data is important to understand as it
dictates when, where, and what text will do when placed in a JSP. This chapter has
yet to introduce any elements, but it has shown a use of template text. The
HelloWorld.jsp example was entirely template text. The corresponding Servlet
generated from HelloWorld.jsp treated this text as static content and sent it as
the content of a response. While HelloWorld.jsp only had one big chunk of tem-
plate text, more complex JSP follow the same rule. Any chunk of template text is
taken and sent directly to a client as it appears on the JSP. Elements on the other
hand are not sent directly to a client. An element is interpreted by a JSP container
and defines special actions that should be taken when generating a response.
Template text does not change, and this little section defines it in total.
Elements are what make JSP dynamic, and elements are further explained
throughout the rest of the chapter. Elements can be broken down into three dif-
ferent categories: scripting elements, directives, and actions. The following self-
named sections explain these elements.
Two Types of Syntax
JSP containers are required to support two different formats of JSP syntax:
normal and XML-compatible. The normal JSP syntax is a syntax designed to be
easy to author. The XML-compatible JSP syntax takes the normal JSP syntax and
modifies it to be XML-compliant
1
. Both syntaxes provide the same functionality,
but the XML-compatible syntax is intended to be more easily used by devel-
opment tools. In the examples of this book the normal JSP syntax is preferred as
it is easily read, understood, and will be familiar if you have used older versions
of JSP.
Just because the XML syntax will not be appearing much in this book’s
examples does not mean it is the lesser of the two syntaxes. The JSP XML syntax
introduced in the JSP 1.2 specification, from a developer’s perspective, is cer-
tainly a hassle to use compared to the regular syntax. This is largely due to the
complexity and strict enforcement of syntax the JSP 1.2 XML syntax had. JSP 2.0
remedies the problem by providing a much more flexible XML syntax. Later on
in the chapter this new, more flexible XML syntax is further explained.
Scripting Elements
The simplest method of making a JSP dynamic is by directly embedding bits of
Java code between blocks of template text by use of scripting elements. In theory
JSP does not limit scripting elements to only those containing Java code, but the
specification only talks about Java as the scripting language, and every container
by default has to support Java. Examples in this book use Java as a scripting lan-
guage. There are three different types of scripting elements available for use in
JSP: scriptlets, expressions, and declarations.

Tuesday, April 26, 2011

Difference Between Servlets and JSP




A clear and important distinction to make about JSP is that coding one is nothing
like coding a Servlet. From what this chapter has explained, it might appear that
JSP is just a simple version of Servlets. In many respects JSP is in fact a simple
method of creating a text-producing Servlet; however, do not be fooled into
thinking this mindset is always true.As the chapter progresses, it will be clear that
JSP and Servlets are two very distinct technologies. Later, after custom tags are
introduced, the degree of separation between the two will seem even larger. The
use of JSP for easily making a Servlet really only applies in the simplest of cases.
To show how vastly different the code for a JSP can be from a Servlet, Listing
displays the code for the JSP equivalent of the HelloWorld Servlet

HelloWorld.jsp
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

They are quite different! You’ll recall the code for HelloWorld.java and
notice the two look nothing alike. The code for the JSP is actually identical to the
text generated by the HelloWorld Servlet, not the source code. Authoring an
HTML-generating JSP is as easy as just authoring the HTML. Compared to using
print() and println()methods in Servlets,the JSP approach is obviously easier.
This is why simple JSP are usually considered a quick method of creating text-
producing Servlets.
Deploying a JSP is also simpler; a Web Application automatically deploys any
JSP to a URL extension that matches the name of the JSP. Test out HelloWorld.jsp
by saving it in the base directory of the jspbook Web Application then browsing to
http://127.0.0.1/jspbook/HelloWorld.jsp

From looking at the results of the example, it certainly does appear Hello
World.jsp is a simple form of HelloWorld.java. What is not shown, but is very
important to understand, is that HelloWorld.jsp is also actually compiled into
equivalent Servlet code. This is done in what is called the translation phase of JSP
deployment and is done automatically by a container. JSP translation both is and
is not something of critical importance for a JSP developer to be aware of. JSP
translation to Servlet source code is important because it explains exactly how a
JSP becomes Java code. While it varies slightly from container to container, all
containers must implement the same JSP life cycle events. Understanding these
life cycle methods helps a JSP developer keep code efficient and thread-safe.
However, JSP translation is not of critical importance because it is always done
automatically by a container. Understanding what a container will do during the
translation phase is good enough to code JSP. Keeping track of the generated
Servlet source code is not a task a JSP developer ever has to do.
JSP translated to Servlet code can be found by looking in the right place for
a particular container. Tomcat stores this code in the /work directory of the
Tomcat installation. Generated code is never pretty, nor does it always have the
same name. Listing 3-2 was taken from HelloWorld$jsp.java in the /work/
localhost/jspbook directory. It is the Servlet code generated for HelloWorld.
jsp that Tomcat automatically compiled and deployed

Tomcat-Generated Servlet Code for HelloWorld.jsp
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;

import javax.servlet.jsp.*;
import org.apache.jasper.runtime.*;
public class HelloWorld$jsp extends HttpJspBase {
static {
}
public HelloWorld$jsp( ) {
}
private static boolean _jspx_inited = false;
public final void _jspx_init() throws
org.apache.jasper.runtime.JspException {
}
public void _jspService(HttpServletRequest request,
HttpServletResponse  response)
throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
String  _value = null;
try {
if (_jspx_inited == false) {
synchronized (this) {
if (_jspx_inited == false) {
_jspx_init();
_jspx_inited = true;
}
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-
8859-1");
pageContext = _jspxFactory.getPageContext(this, request,
response,
"", true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
// HTML // begin
[file="/HelloWorld.jsp";from=(0,0);to=(8,0)]
out.write("<html>\r\n<head>\r\n<title>Hello
World!</title>\r\n</head>\r\n<body>\r\n<h1>Hello
World!</h1>\r\n</body>\r\n</html>\r\n");
// end
} catch (Throwable t) {
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (pageContext != null)
pageContext.handlePageException(t);
} finally {
if (_jspxFactory != null)
_jspxFactory.releasePageContext(pageContext);
}
}
}



Do not bother trying to read through and understand the generated code.
The important point to understand is that a container handles a JSP as a Servlet
but does so behind the scenes
. This ties directly back to the greater point that JSP
are really just Servlets. The difference between the two technologies is not in the
life cycles or how a container manages them at runtime. The difference between
Servlets and JSP is the syntax they offer for creating the same functionality. With
JSP it is almost always simpler to create text-producing Servlets, but normal
Servlets are still best suited for sending raw bytes to a client or when complete
control is needed over Java source code.