Web Applications

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Web Applications

JSP Scripting Elements


Scripting Elements

JSP scripting elements let you insert code into the servlet that will be generated from the JSP page.
There are three forms:
1. Expressions of the form <%= expression %>, which are evaluated and inserted into the
servlet’s output
2. Scriptlets of the form <% code %>, which are inserted into the servlet’s _jspService
method (called by service)
3. Declarations of the form <%! code %>, which are inserted into the body of the servlet
class, outside of any existing methods Each of these scripting elements is described in more
detail in the following sections.
Template Text

In many cases, a large percentage of your JSP page just consists of static HTML,
known as template text. In almost all respects, this HTML looks just like normal HTML,
follows all the same syntax rules, and is simply “passed through” to the client by the
servlet created to handle the page. Not only does the HTML look normal, it can be
created by whatever tools you already
are using for building Web pages.

There are two minor exceptions to the “template text is passed straightthrough”
rule. First, if you want to have <% in the output, you need to put <\% in the template
text. Second, if you want a comment to appear in the JSP page but not in the resultant
document, use <%-- JSP Comment --%>
HTML comments of the form <!-- HTML Comment --> are passed through to the
resultant HTML normally.
JSP Expressions

A JSP expression is used to insert values directly into the output. It has the following
form:
<%= Java Expression %>
The expression is evaluated, converted to a string, and inserted in the page. This
evaluation is performed at run time (when the page is requested)
and thus has full access to information about the request. For example, the following
shows the date/time that the page was requested:
Current time: <%= new java.util.Date() %>
Predefined Variables
To simplify these expressions, you can use a number of predefined variables.
These implicit objects are discussed in more detail in Section 10.5, but for
the purpose of expressions, the most important ones are:
• request, the HttpServletRequest
• response, the HttpServletResponse
• session, the HttpSession associated with the request (unless disabled with the
session attribute of the page directive — see Section 11.4)
• out, the PrintWriter (a buffered version called JspWriter) used to send output to
the client

Here is an example: Your hostname: <%= request.getRemoteHost() %>


XML Syntax for Expressions

XML authors can use the following alternative syntax for JSP expressions:
<jsp:expression>
Java Expression
</jsp:expression>

Note that XML elements, unlike HTML ones, are case sensitive, so be sure to use
jsp:expression in lower case.
Using Expressions as Attribute
Values
As we will see later, JSP includes a number of elements that use XML syntax to
specify various parameters.
For example, the following example passes "Marty" to the setFirstName method of
the object bound to the author variable. My purpose here is simply to point out
the use of the name, property, and value attributes.
<jsp:setProperty name="author" property="firstName" value="Marty" />
Most attributes require the value to be a fixed string enclosed in either single or
double quotes, as in the example above. A few attributes, however, permit you to
use a JSP expression that is computed at request time. The value attribute of
jsp:setProperty is one such example, so the following code is perfectly legal :
<jsp:setProperty name="user"
property="id"
value=’<%= "UserID" + Math.random() %>’ />
Example
The folowing listing gives an example JSP page; http://www.coreservlets.com/.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">


<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="author" CONTENT="Marty Hall">
<META NAME="keywords"
CONTENT="JSP,expressions,JavaServer,Pages,servlets">
<META NAME="description"
CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>
JSP Scriptlets
If you want to do something more complex than insert a simple expression, JSP scriptlets let
you insert arbitrary code into the servlet’s _jspService method (which is called by
service). Scriptlets have the following form:
<% Java Code %>

Scriptlets have access to the same automatically defined variables as expressions ( request,
response, session, out, etc.; see Section 10.5). So, for example, if you want output to
appear in the resultant page, you would use the out variable, as in the following example.
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
In this particular instance, you could have accomplished the same effect more easily by using
the following JSP expression:
Attached GET data: <%= request.getQueryString() %>

In general, however, scriptlets can perform a number of tasks that cannot be
accomplished with expressions alone. These tasks include setting response
headers and status codes, invoking side effects such as writing to the server log or
updating a database, or executing code that contains loops, conditionals, or other
complex constructs. For instance, the following snippet specifies that the current
page is sent to the client as plain text, not as HTML (which is the default).
<% response.setContentType("text/plain"); %>


It is important to note that you can set response headers or status codes at various
places within a JSP page, even though this capability appears to violate the rule
that this type of response data needs to be specified before any document content
is sent to the client.

Setting headers and status codes is permitted because servlets that result from JSP
pages use a special type of PrintWriter (of the more specific class JspWriter) that
buffers the document before sending it. This buffering behavior can be changed,
however; using autoflush attribute of the page directive.

As an example of executing code that is too complex for a JSP expression, The
following listing presents a JSP page that uses the bgColor request parameter to
set the background color of the page:
// BGColor.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Color Testing</TITLE>
</HEAD>
<%
String bgColor = request.getParameter("bgColor");
boolean hasExplicitColor;
if (bgColor != null) {
hasExplicitColor = true;
} else {
hasExplicitColor = false;
bgColor = "WHITE";
}
%>
<BODY BGCOLOR="<%= bgColor %>">
<H2 ALIGN="CENTER">Color Testing</H2>
<%
if (hasExplicitColor) {
out.println("You supplied an explicit background color of " +
bgColor + ".");
} else {
out.println("Using default background color of WHITE. " +
"Supply the bgColor request attribute to try " +
"a standard color, an RRGGBB value, or to see " +
"if your browser supports X11 color names.");
}
%>
</BODY>
</HTML>
Using Scriptlets to Make Parts of the JSP File
Conditional
Another use of scriptlets is to conditionally include standard HTML and JSP constructs. The key to
this approach is the fact that code inside a scriptlet gets inserted into the resultant servlet’s
_jspService method (called by service) exactly as written, and any static HTML (template text)
before or after a scriptlet gets converted to print statements. This means that scriptlets need not
contain complete Java statements, and blocks left open can affect the static HTML or JSP outside
of the scriptlets.
For example, consider the following JSP fragment containing mixed template text and scriptlets.
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>
When converted to a servlet by the JSP engine, this fragment will result in something similar to the
following.
if (Math.random() < 0.5) {
out.println("Have a <B>nice</B> day!");
} else {
out.println("Have a <B>lousy</B> day!");
}
Special Scriptlet Syntax
There are two special constructs you should take note of. First, if you
want to use the characters %> inside a scriptlet, enter %\> instead.
Second, the XML
equivalent of <% Code %> is
<jsp:scriptlet>
Code
</jsp:scriptlet>
The two forms are treated identically by JSP engines.
JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the
main body of the servlet class (outside of the _jspService method that is
called by service to process the request). A declaration has the following
form:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in
conjunction with JSP expressions or scriptlets. For example, here is a JSP
fragment that prints the number of times the current page has been
requested since the server was booted (or the servlet class was changed and
reloaded). Recall that multiple client requests to the same servlet result only in
multiple threads calling the service method of a single servlet instance.
They do not result in the creation of multiple servlet instances except possibly
when the servlet implements SingleThreadModel.
Thus, instance variables (fields) of a servlet are shared by multiple requests
and accessCount does not have to be declared static below.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>JSP Declarations</TITLE>
<META NAME="author" CONTENT="Marty Hall">
<META NAME="keywords"
CONTENT="JSP,declarations,JavaServer,Pages,servlets">
<META NAME="description" CONTENT="A quick example of JSP
declarations.">
<LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css">
</HEAD>
<BODY>
<H1>JSP Declarations</H1>
<%! private int accessCount = 0; %>
<H2>Accesses to page since server reboot:
<%= ++accessCount %></H2>
</BODY>
</HTML>
Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with
eight automatically defined variables, sometimes called implicit objects.
Since JSP declarations (see Section 10.4) result in code that appears
outside of the _jspService method, these variables are not accessible in
declarations. The available variables are request, response, out, session,
application, config, pageContext, and page. Details for each are given
below.
request response
out application
config pageContext
page
request
This variable is the HttpServletRequest associated with the
request; it gives you access to the request parameters, the
request type (e.g., GET or POST), and the incoming HTTP
headers (e.g., cookies).

Strictly speaking, if the protocol in the request is something


other than HTTP, request is allowed to be a subclass of
ServletRequest other than HttpServletRequest. However,
few, if any, JSP servers currently support non-HTTP
servlets.
response
This variable is the HttpServletResponse associated with the response to
the client. Note that since the output stream (see out) is normally
buffered, it is legal to set HTTP status codes and response headers in
JSP pages, even though the setting of headers or status codes is not
permitted in servlets once any output has been sent to the client.
out

This is the PrintWriter used to send output to the client. However,


to make the response object useful, this is a buffered version of
Print-Writer called JspWriter. You can adjust the buffer size
through use of the buffer attribute of the page directive.
Also note that out is used almost exclusively in scriptlets, since
JSP expressions are automatically placed in the output stream
and thus rarely need to refer to out explicitly.
session

This variable is the HttpSession object associated with the request.


Recall that sessions are created automatically, so this variable is
bound even if there is no incoming session reference.

The one exception is if you use the session attribute of the page
directive to turn sessions off. In that case, attempts to reference
the session variable cause errors at the time the JSP page is
translated into a servlet.
application
This variable is the ServletContext as obtained via getServletConfig().
getContext(). Servlets and JSP pages can store persistent data
in the ServletContext object rather than in instance variables.
ServletContext has setAttribute and getAttribute methods that let you
store arbitrary data associated with specified keys. The difference
between storing data in instance variables and storing it in the
Servlet-Context is that the ServletContext is shared by all servlets in
the servlet engine (or in the Web application, if your server supports
such a
capability).
config
This variable is the ServletConfig object for this page.
pageContext

JSP introduced a new class called PageContext to give a single point of


access to many of the page attributes and to provide a convenient
place to store shared data.

The pageContext variable stores the value of the PageContext object


associated with the current page. Refer to (Sharing Beans) for a
discussion of its use.
page

This variable is simply a synonym for this and is not very useful in the
Java programming language. It was created as a place holder for the
time when the scripting language could be something other than Java.

You might also like