JSP Basics
JavaServer Pages (JSP) is another Java technology for
developing web applications. JSP was released during the time servlet
technology had gained popularity as one of the best web technologies available.
JSP is not meant to replace servlets, however. In fact, JSP is an extension of the
servlet technology, and it is common practice to use both servlets and JSP
pages in the same web applications.
Authoring JSP pages is so easy that you can write JSP
applications without much knowledge of the underlying API. If you want to be a
really good Java web programmer, however, you need to know both JSP and
servlets. Even if you use only JSP pages in your Java web applications,
understanding servlets is still very important. As you will see in this chapter
and the chapters to come, JSP uses the same techniques as those found in
servlet programming. For example, in JSP you work with HTTP requests and HTTP
responses, request parameters, request attributes, session management, cookies,
URL-rewriting, and so on. This chapter explains the relation between JSP and
servlets, introduces the JSP technology, and presents many examples that you
can run easily.
Note
If you are not familiar with servlet technology, read
this chapter only after reading Chapters 1 to 7, which focus specifically on
creating and working with servlets.
What's Wrong with Servlets?
The history of web server-side programming in Java
started with servlets. Sun introduced servlets in 1996 as small Java-based
applications for adding dynamic content to web applications. Not much later,
with the increasing popularity of Java, servlets took off to become one of the
most popular technologies for Internet development today.
Servlet programmers know how cumbersome it is to
program with servlets, however, especially when you have to send a long HTML
page that includes little code. Take the snippet in Listing
8.1 as an
example. The code is a fragment from a servlet-based application that displays
all parameter names and values in an HTTP request.
Listing 8.1 Displays All Parameter/Value Pairs in a
Request Using a Servlet
import
javax.servlet.*;
import
javax.servlet.http.*;
import
java.io.*;
import
java.util.*;
public class
MyDearServlet extends HttpServlet {
//Process
the HTTP GET request
public void
doGet(HttpServletRequest request,
HttpServletResponse
response)
throws
ServletException, IOException {
doPost(request,
response);
}
//Process
the HTTP POST request
public void
doPost(HttpServletRequest request,
HttpServletResponse
response)
throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter
out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Using
Servlets</TITLE></HEAD>");
out.println("<BODY
BGCOLOR=#123123>");
//Get
parameter names
Enumeration
parameters = request.getParameterNames();
String param
= null;
while
(parameters.hasMoreElements()) {
param =
(String) parameters.nextElement();
out.println(param
+ ":" + request.getParameter(param) +
"<BR>");
}
out.println("</BODY>");
out.println("</HTML>");
out.close();
} //End of
doPost method
/* other
parts of the class goes here
.
.
.
*/
} //End of
class
Nearly half of the content sent from the doPost method
is static HTML. However, each HTML tag must be embedded in a String and sent
using the println method of the PrintWriter object. It is a tedious chore.
Worse still, the HTML page may be much longer.
Another disadvantage of using servlets is that every
single change will require the intervention of the servlet programmer. Even a
slight graphical modification, such as changing the value of the <BODY>
tag's BGCOLOR attribute from #DADADA to #FFFFFF, will need to be done by the
programmer (who in this case will work under the supervision of the more
graphic-savvy web designer).
Sun understood this problem and soon developed a
solution. The result was JSP technology. According to Sun's web site, "JSP
technology is an extension of the servlet technology created to support
authoring of HTML and XML pages." Combining fixed or static template data
with dynamic content is easier with JSP. Even if you're comfortable writing
servlets, you will find in this chapter several compelling reasons to investigate
JSP technology as a complement to your existing work.
What needs to be highlighted is that "JSP
technology is an extension of the servlet technology." This means that JSP
did not replace servlets as the technology for writing server-side
Internet/intranet applications. In fact, JSP was built on the servlet
foundation and needs the servlet technology to work.
JSP solves drawbacks in the servlet technology by
allowing the programmer to intersperse code with static content, for example.
If the programmer has to work with an HTML page template written by a web
designer, the programmer can simply add code into the HTML page and save it as
a .jsp file. If at a later stage the web designer needs to change the HTML body
background color, he or she can do it without wasting the charging-by-the-hour
programmer's time. He or she can just open the .jsp file and edit it
accordingly.
Listing 8.2 Displays All Parameter/Value Pairs in a
Request Using JSP
<%@ page
import="java.util.Enumeration" %>
<HTML>
<HEAD><TITLE>Using
JSP</TITLE></HEAD>
<BODY
BGCOLOR=#DADADA>
<%
//Get parameter
names
Enumeration
parameters = request.getParameterNames();
String param
= null;
while
(parameters.hasMoreElements()) {
param =
(String) parameters.nextElement();
out.println(param
+ ":" + request.getParameter(param) +
"<BR>");
}
out.close();
%>
</BODY>
</HTML>
You can see that <HTML> tags stay as they are.
When you need to add dynamic content, all you need to do is enclose your code
in <% … %> tags.
Again, JSP is not a replacement for servlets. Rather,
JSP technology and servlets together provide an attractive solution to web
scripting/programming by offering platform independence, enhanced performance,
separation of logic from display, ease of administration, extensibility into
the enterprise, and most importantly, ease of use.
Running Your First JSP
This section invites you to write a simple JSP page
and run it. The emphasis here is not on the architecture or syntax and
semantics of a JSP page; instead the section demonstrates how to configure
minimally the servlet/JSP container to run JSP. Tomcat 4 is used to run JSP
applications. If you have installed and configured Tomcat 4 for your servlet
applications, there is no more to do. If you haven't, see Appendix
A,
"Tomcat Installation and Configuration."
Note
In the JSP context, Tomcat is often referred to as a
"JSP container." Because Tomcat also is used to run servlets,
however, it is more common to call it a servlet/JSP container.
After reading this section, you will understand how
much JSP simplifies things for servlets. To make your JSP page run, all you
need to do is configure your JSP container (Tomcat) and write a JSP page.
Configuration is only done once, at the beginning. No compilation is necessary.
Configuring Tomcat to Run a JSP Application
The first thing you need to do before you can run your
JSP application is configure Tomcat so that it recognizes your JSP application.
To configure Tomcat to run a particular JSP application, follow these steps:
- Create a directory under %CATALINA_HOME%/webapps
called myJSPApp. The directory structure is shown in Figure 8.1.
Figure 8.1. The JSP application directory structure
for the myJSPApp application.
- Add a subdirectory named WEB-INF under the
myJSPApp directory.
- Edit server.xml, the server configuration file,
so Tomcat knows about this new JSP application. The server.xml file is
located in the conf directory under %CATALINA_HOME%. Open the file with
your text editor and look for code similar to the following:
4.
<Context
path="/examples" docBase="examples" debug="0"
5.
reloadable="true">
6.
.
7.
.
8.
.
</Context>
Right after the closing tag </Context>, add the
following code:
<Context
path="/myJSPApp" docBase="myJSPApp" debug="0"
reloadable="true">
</Context>
4. Restart Tomcat.
Now you can write your JSP file and store it under the
myJSPApp file. Alternatively, to make it more organized, you can create a
subdirectory called jsp under myJSPApp and store your JSP files there. If you
do this, you don't need to change the setting in the server.xml file.
Writing a JSP File
A JSP page consists of interwoven HTML tags and Java
code. The HTML tags represent the presentation part and the code produces the
contents. In its most basic form, a JSP page can include only the HTML part,
like the code shown in Listing
8.3.
Listing 8.3 The Simplest JSP Page
<HTML>
<HEAD>
</HEAD>
<BODY>
JSP is easy.
</BODY>
</HTML>
Save this file as SimplePage.jsp in the myJSPApp
directory. Your directory structure should resemble Figure
8.1.
Now, start your web browser, and type the following
URL:
http://localhost:8080/myJSPApp/SimplePage.jsp
Figure 8.2. Your first JSP page.
Other Examples
Of course, the code in Listing
8.3 is not a
really useful page, but it illustrates the point that a JSP page does not need
to have code at all. If your page is purely static, like the one in Listing
8.3, you
shouldn't put it in a JSP file because JSP files are slower to process than
HTML files. You might want to use a JSP file for pure HTML tags, however, if
you think the code might include Java code in the future. This saves you the
trouble of changing all the links to this page at the later stage.
To write Java code in your JSP file, you embed the
code in <% … %> tags. For example, the code in Listing
8.4 is an
example of intertwining Java code and HTML in a JSP file.
Listing 8.4 Interweaving HTML and Code
<HTML>
<HEAD>
</HEAD>
<BODY>
<%
out.println("JSP
is easy");
%>
</BODY>
</HTML>
The code in Listing
8.4 produces
the same output as the one in Listing
8.3. Notice,
however, the use of the Java code to send the text. If you don't understand
what out.println does, bear with me for a moment—it is discussed in detail in
the next section. For now, knowing that out.println is used to send a String to
the web browser is sufficient.
Notice also that the output of a JSP page is plain
text consisting of HTML tags. No code section of the page will be sent to the
browser.
Another example is given in Listing
8.5. This
snippet displays the string "Welcome. The server time is now"
followed by the server time.
Listing 8.5 Displaying the Server Time
<HTML>
<HEAD>
<TITLE>Displaying
the server time</TITLE>
</HEAD>
<BODY>
Welcome. The
server time is now
<%
java.util.Calendar
now = java.util.Calendar.getInstance();
int hour =
now.get(java.util.Calendar.HOUR_OF_DAY);
int minute =
now.get(java.util.Calendar.MINUTE);
if
(hour<10)
out.println("0"
+ hour);
else
out.println(hour);
out.println(":");
if
(minute<10)
out.println("0"
+ minute);
else
out.println(minute);
%>
</BODY>
</HTML>
The code in Listing
8.5 displays
the time in the hh:mm format. Therefore, if the hour is less than 10, a
"0" precedes, which means that nine will be displayed as 09 instead
of 9.
How JSP Works
Inside the JSP container is a special servlet called
the page compiler. The servlet container is configured to forward to this page
compiler all HTTP requests with URLs that match the .jsp file extension. This
page compiler turns a servlet container into a JSP container. When a .jsp page
is first called, the page compiler parses and compiles the .jsp page into a
servlet class. If the compilation is successful, the jsp servlet class is
loaded into memory. On subsequent calls, the servlet class for that .jsp page
is already in memory; however, it could have been updated. Therefore, the page compiler
servlet will always compare the timestamp of the jsp servlet with the jsp page.
If the .jsp page is more current, recompilation is necessary. With this
process, once deployed, JSP pages only go through the time-consuming
compilation process once.
You may be thinking that after the deployment, the
first user requests for a .jsp page will experience unusually slow response due
to the time spent for compiling the .jsp file into a jsp servlet. To avoid this
unpleasant situation, a mechanism in JSP allows the .jsp pages to be
pre-compiled before any user request for them is received. Alternatively, you
deploy your JSP application as a web archive file in the form of a compiled
servlet. This technique is discussed in Chapter
16,
"Application Deployment."
The JSP Servlet Generated Code
When the JSP is invoked, Tomcat creates two files in
the C:\%CATALINA_HOME%\work\localhost\examples\jsp directory. Those two files
are SimplePage_ jsp.java and SimplePage_ jsp.class. When you open the
SimplePage_ jsp.java file, you will see the following:
package
org.apache.jsp;
import
javax.servlet.*;
import
javax.servlet.http.*;
import
javax.servlet.jsp.*;
import
javax.servlet.jsp.tagext.*;
import
org.apache.jasper.runtime.*;
public class
SimplePage_jsp extends HttpJspBase {
static {
}
public
SimplePage_jsp( ) {
}
private
static boolean _jspx_inited = false;
public final
void _jspx_init() throws org.apache.jasper.JasperException {
}
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();
// begin
[file="C:\\tomcat4\\bin\\..\\webapps\\examples\\jsp\\SimplePage.jsp";from=(0,
2);to=(2,0)]
out.println("JSP
is easy");
// end
// HTML //
begin
[file="C:\\tomcat4\\bin\\..\\webapps\\examples\\jsp\\SimplePage.jsp";from=(2,
2);to=(3,0)]
out.write("\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);
}
}
}
For now, I will defer a full explanation of the
preceding code until you learn more about how the interfaces and classes are
used to run a JSP page. You can read the section, "The
Generated Servlet Revisited," later in this chapter, to learn more about the
code listed here.
The JSP API
The JSP technology is based on the JSP API that
consists of two packages: javax.servlet.jsp and javax.servlet.jsp.tagext. Both
packages are given in detail in Appendix
D, "The
javax.servlet.jsp Package Reference," and Appendix
E, "The
javax.servlet.jsp.tagext Package Reference." This chapter will discuss the
classes and interfaces of the javax.servlet.jsp package and
javax.servlet.jsp.tagext will be discussed in Chapter
11,
"Using JSP Custom Tags."
In addition to these two packages, JSP also needs the
two servlet packages—javax.servlet and javax.servlet.http. When you study the javax.servlet.jsp
package, you will know why we say that JSP is an extension of servlet
technology and understand why it is important that a JSP application programmer
understands the servlet technology well.
The javax.servlet.jsp package has two interfaces and
four classes. The interfaces are as follows:
- JspPage
- HttpJspPage
The four classes are as follows:
- JspEngineInfo
- JspFactory
- JspWriter
- PageContext
In addition, there are also two exception classes:
JspException and JspError.
The JspPage Interface
The JspPage is the interface that must be implemented
by all JSP servlet classes. This may remind you of the javax.servlet.Servlet
interface in Chapter
1, "The
Servlet Technology," of course. And, not surprisingly, the JspPage
interface does extend the javax.servlet.Servlet interface.
The JSPPage interface has two methods, JspInit and JspDestroy,
whose signatures are as follows:
public void
jspInit()
public void
jspDestroy()
jspInit, which is similar to the init method in the
javax.servlet.Servlet interface, is called when the JspPage object is created
and can be used to run some initialization. This method is called only once
during the life cycle of the JSP page: the first time the JSP page is invoked.
The jspDestroy method is analogous with the destroy
method of the javax.servlet.Servlet interface. This method is called before the
JSP servlet object is destroyed. You can use this method to do some clean-up,
if you want.
Most of the time, however, JSP authors rarely make
full use of these two methods. The following example illustrates how you can
implement these two methods in your JSP page:
<%!
public void
jspInit() {
System.out.println("Init");
}
public void
jspDestroy() {
System.out.println("Destroy");
}
%>
<%
out.println("JSP
is easy");
%>
Notice that the first line of the code starts with
<%!. You will find the explanation of this construct in the Chapter
9, "JSP
Syntax."
The HttpJspPage Interface
This interface directly extends the JspPage interface.
There is only one method: _ jspService. This method is called by the JSP
container to generate the content of the JSP page. The _ jspService has the
following signature:
public void
_jspService(HttpServletRequest request,
HttpServletResponse
response) throws ServletException, IOException.
You can't include this method in a JSP page, such as
in the following code:
<%!
public void
jspInit() {
System.out.println("Init");
}
public void
jspDestroy() {
System.out.println("Destroy");
}
public void
_jspService(HttpServletRequest request,
HttpServletResponse
response) throws ServletException, IOException {
System.out.println("Service");
}
%>
This is because the page content itself represents
this method. See the section "The
Generated Servlet Revisited."
The JspFactory Class
The JspFactory class is an abstract class that
provides methods for obtaining other objects needed for the JSP page
processing. The class has the static method getDefaultFactory that returns a
JspFactory object. From the JspFactory object, a PageContext and a
JspEngineInfo object can be obtained that are useful for the JSP page
processing. These objects are obtained using the JspFactory class's
getEngineInfo method and the getPageContext method, whose signatures are given
here:
public
abstract JspEngineInfo getEngineInfo()
public
abstract PageContext getPageContext (
Servlet
requestingServlet, ServletRequest request,
ServletResponse
response, String errorPageURL,
boolean
needsSession, int buffer, boolean autoFlush)
The following code is part of the _ jspService method
that is generated by the JSP container:
JspFactory
_jspxFactory = null;
PageContext
pageContext = null;
jspxFactory
= JspFactory.getDefaultFactory();
.
.
.
pageContext
= _jspxFactory.getPageContext(this, request,
response, "", true, 8192, true);
The JspEngineInfo Class
The JspEngineInfo class is an abstract class that
provides information on the JSP container. Only one method,
getSpecificationVersion, returns the JSP container's version number. Because
this is the only method currently available, this class does not have much use.
You can obtain a JspEngineInfo object using the
getEngineInfo method of the JspFactory class.
The PageContext Class
PageContext represents a class that provides methods
that are implementation-dependent. The PageContext class itself is abstract, so
in the _ jspService method of a JSP servlet class, a PageContext object is
obtained by calling the getPageContext method of the JspFactory class.
The PageContext class provides methods that are used
to create other objects. For example, its getOut method returns a JspWriter
object that is used to send strings to the web browser. Other methods that
return servlet-related objects include the following:
- getRequest, returns a ServletRequest object
- getResponse, returns a ServletResponse object
- getServletConfig, returns a ServletConfig object
- getServletContext, returns a ServletContext
object
- getSession, returns an HttpSession object
The JspWriter Class
The JspWriter class is derived from the java.io.Writer
class and represents a Writer that you can use to write to the client browser.
Of its many methods, the most important are the print and println methods. Both
provide enough overloads that ensure you can write any type of data. The
difference between print and println is that println always adds the new line
character to the printed data.
Additional methods allow you to manipulate the buffer.
For instance, the clear method clears the buffer. It throws an exception if
some of the buffer's content has already been flushed. Similar to clear is the
clearBuffer method, which clears the buffer but never throws any exception if
any of the buffer's contents have been flushed.
The Generated Servlet Revisited
Now that you understand the various interfaces and
classes in the javax.servlet.jsp package, analyzing the generated JSP servlet
will make more sense.
When you study the generated code, the first thing
you'll see is the following:
public class
SimplePage_jsp extends HttpJspBase {
The discussion should start with the questions,
"What is HttpJspBase?"and "Why doesn't the JSP servlet class
implement the javax.servlet.jsp.JspPage or javax.servlet.jsp.HttpJspPage
interface?"
First, remember that the JSP specification defines
only standards for writing JSP pages. A JSP page itself will be translated into
a java file, which in turn will be compiled into a servlet class. The two
processes are implementation dependent and do not affect the way a JSP page
author codes. Therefore, a JSP container has the freedom and flexibility to do
the page translation in its own way. The JSP servlet-generated code presented
in this chapter is taken from Tomcat. You can therefore expect a different Java
file to be generated by other JSP containers.
In Tomcat, HttpJspBase is a class whose source can be
found under the src\jasper\src\share\org\apache\jasper\runtime directory under
the %CATALINA_HOME% directory.
Most importantly, the signature of this class is as
follows:
public
abstract class HttpJspBase extends HttpServlet
implements
HttpJspPage
Now you can see that HttpJspBase is an HttpServlet and
it does implement the javax.servlet.jsp.HttpJspPage interface. The HttpJspBase
is more like a wrapper class so that its derived class does not have to provide
implementation for the interface's methods if the JSP page author does not
override them. The complete listing of the class follows:
/*
* The Apache
Software License, Version 1.1
*
* Copyright
(c) 1999 The Apache Software Foundation.
All rights
* reserved.
*
*
Redistribution and use in source and binary forms, with or without
*
modification, are permitted provided that the following conditions
* are met:
*
* 1.
Redistributions of source code must retain the above copyright
* notice, this list of conditions and the
following disclaimer.
*
* 2.
Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the
following disclaimer in
* the documentation and/or other materials
provided with the
* distribution.
*
* 3. The
end-user documentation included with the redistribution, if
* any, must include the following
acknowlegement:
* "This product includes software
developed by the
* Apache Software Foundation
(http://www.apache.org/)."
* Alternately, this acknowlegement may appear
in the software itself,
* if and wherever such third-party
acknowlegements normally appear.
*
* 4. The
names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to
endorse or promote products derived
* from this software without prior written
permission. For written
* permission, please contact
apache@apache.org.
*
* 5.
Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their
names without prior written
* permission of the Apache Group.
*
* THIS
SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*
DISCLAIMED. IN NO EVENT SHALL THE APACHE
SOFTWARE FOUNDATION OR
* ITS
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH
DAMAGE.
*
====================================================================
*
* This
software consists of voluntary contributions made by many
*
individuals on behalf of the Apache Software Foundation. For more
*
information on the Apache Software Foundation, please see
*
<http://www.apache.org/>.
*
*/
package
org.apache.jasper.runtime;
import
java.io.IOException;
import
java.io.FileInputStream;
import
java.io.InputStreamReader;
import
java.net.URL;
import
java.net.MalformedURLException;
import
javax.servlet.*;
import
javax.servlet.http.*;
import
javax.servlet.jsp.*;
import
org.apache.jasper.JasperException;
import
org.apache.jasper.Constants;
/**
* This is
the subclass of all JSP-generated servlets.
*
* @author
Anil K. Vijendran
*/
public
abstract class HttpJspBase extends HttpServlet
implements
HttpJspPage {
protected
PageContext pageContext;
protected
HttpJspBase() {
}
public final
void init(ServletConfig config)
throws
ServletException {
super.init(config);
jspInit();
}
public
String getServletInfo() {
return
Constants.getString ("jsp.engine.info");
}
public final
void destroy() {
jspDestroy();
}
/**
* Entry
point into service.
*/
public final
void service(HttpServletRequest request,
HttpServletResponse
response)
throws
ServletException, IOException {
_jspService(request,
response);
}
public void
jspInit() {
}
public void
jspDestroy() {
}
public
abstract void _jspService(HttpServletRequest request,
HttpServletResponse
response)
throws
ServletException, IOException;
}
Back to the generated JSP servlet class, remember that
the JSP page source code is simply the following three lines of code:
<%
out.println("JSP
is easy");
%>
There are no jspInit and jspDestroy methods in the
source code, so there are no implementations for these two methods in the
resulting servlet code. The three lines of code, however, translate into the _
jspService method. For reading convenience, the method is reprinted here.
Notice that, for clarity, the comments have been removed.
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();
out.println("JSP
is easy");
out.write("\r\n");
}
catch
(Throwable t) {
if (out !=
null && out.getBufferSize() != 0)
out.clearBuffer();
if
(pageContext != null)
pageContext.handlePageException(t);
}
finally {
if
(_jspxFactory != null)
_jspxFactory.releasePageContext(pageContext);
}
}
Implicit Objects
Having examined the generated JSP servlet source code,
you know that the code contains several object declarations in its _ jspService
method. Recall this part from the code in the preceding section:
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 {
.
.
.
_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();
.
.
.
}
You see that there are object references, such as
pageContext, session, application, config, out, and so on. These object
references are created whether they are used from inside the page. They are
automatically available for the JSP page author to use! These objects are
called implicit objects and are summarized in the Table
8.1.
|
Table 8.1. JSP Implicit Objects
|
|
|
Object
|
Type
|
|
request
|
javax.servlet.http.HttpServletRequest
|
|
response
|
javax.servlet.http.HttpServletResponse
|
|
out
|
javax.servlet.jsp.JspWriter
|
|
session
|
javax.servlet.http.HttpSession
|
|
application
|
javax.servlet.ServletContext
|
|
config
|
javax.servlet.ServletConfig
|
|
pageContext
|
javax.servlet.jsp.PageContext
|
|
page
|
javax.servlet.jsp.HttpJspPage
|
|
exception
|
java.lang.Throwable
|
<%
out.println("JSP
is easy.");
%>
In the case of the code above, you use the implicit
object out that represents a javax.servlet.jsp.JspWriter. All the implicit
objects are discussed briefly in the following subsections.
request and response Implicit Objects
In servlets, both objects are passed in by the servlet
container to the service method of the javax.servlet.http.HttpServlet class.
Remember its signature?
protected
void service(HttpServletRequest request,
HttpServletResponse
response)
throws
ServletException, IOException
Note
If you want to review servlets, you can go back to
Chapters 1, "The Servlet
Technology," and Chapter
2,"
Inside Servlets," for more details.
In a servlet, before you send any output, you are
required to call the setContentType of the HttpServletResponse to tell the
browser the type of the content, as in the following code:
response.setContentType("text/html");
In JSP, this is done automatically for you in the
generated JSP servlet class, as follows:
response.setContentType("text/html;charset=ISO-8859-1");
Having an HttpServletRequest and an
HttpServletResponse, you can do anything you like as you would in a servlet. For
example, the following JSP page retrieves the value of a parameter called
firstName and displays it in the browser:
<HTML>
<HEAD>
<TITLE>Simple
Page</TITLE>
</HEAD>
<BODY>
<%
String
firstName = request.getParameter("firstName");
out.println("First
name: " + firstName);
%>
</BODY>
</HTML>
The following example uses the sendRedirect method of
the javax.servlet.http.HttpServletResponse to redirect the user to a different
URL:
<%
response.sendRedirect("http://www.newriders.com");
%>
out Implicit Object
out is probably the most frequently used implicit
object. You call either its print method or its println method to send text or
other data to the client browser. In a servlet, you always need to call the
getWriter method of the javax.servlet.http.HttpServletResponse interface to
obtain a PrintWriter before you can output anything to the browser, as follows:
PrintWriter
out = response.getWriter();
In JSP, you don't need to do this because you already
have an out that represents a javax.servlet.jsp.JspWriter object.
session Implicit Object
The session implicit object represents the HttpSession
object that you can retrieve in a servlet by calling the getSession method of
the javax.servlet.http.HttpServletRequest interface, as in the following code:
request.getSession();
The following code is a JSP page that uses a session
object to implement a counter:
<HTML>
<HEAD>
<TITLE>Counter</TITLE>
</HEAD>
<BODY>
<%
String
counterAttribute = (String) session.getAttribute("counter");
int count =
0;
try {
count =
Integer.parseInt(counterAttribute);
}
catch
(Exception e) {
}
count++;
session.setAttribute("counter",
Integer.toString(count));
out.println("This
is the " + count + "th time you visited this page in this
session.");
%>
</BODY>
</HTML>
See how session is readily available without efforts
from the programmer's side?
Warning
Note that the session object is available only in a
JSP page that participates in the session management. To decide whether or not
your JSP page should participate in the session management, see the discussion
of the session management as discussed in Chapter
5,
"Session Management."
application
The application implicit object represents the
javax.servlet.ServletContext object. In an HttpServlet, you can retrieve the
ServletContext method by using the getServletContext method.
config
The config implicit object represents a
javax.servlet.ServletConfig object that in a servlet can be retrieved by using
the getServletConfig method.
pageContext
The pageContext implicit object represents the
javax.servlet.jsp.PageContext object discussed in the section, "The
PageContext Class."
page
The page implicit object represents the
javax.servlet.jsp.HttpJspPage interface explained in the section, "The
HttpJspPage Interface."
Exception
The exception object is available only on pages that
have been defined as error pages.