Anda di halaman 1dari 71

Unit III

Chapter 1 :Java Servlets:

Java servlets allow users to run Java code on the server and send HTML pages to a browser.
The Java Servlet API allows a software developer to add dynamic content to a web server using the
Java platform.
The generated content is commonly HTML, but may be other data such as XML.

Introduction to Servlets

 Servlets are Java programs running on a web server that produce results viewed remotely
on web server.
 Servlets has the same purpose that PHP or CGI had in the past.

 We shall describe how Servlet works with some examples.

 You will also learn about Servlet Response and Request Model, Servlet Life Cycle, Servlet
Scope Objects and Error Handling.

What are Java Servlets?

Servlets are Java technology's answer to the CGI programming. They are programs that run on a
Web server and build Web page. Building Web pages on the fly is useful (and commonly done) for
a number of reason:

 The Web page is based on the data submitted by the user. For example the result pages
from search engines are generated this way, and programs that process orders for e-
commerce sites do this as well.
 The data alsp changes frequently. For example, a weather-report or news headlines page
might build the page dynamically, perhaps returning a previously built page if it is still up
to the date.

The Web page uses information from corporate databases or other such source. For example,
you would use this for making a Web page at an on-line store that lists current prices and number
of items in the stock.

1
What are the Advantage of Servlets Over "Traditional" CGI?

Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than
traditional CGI and than many alternative CGI-like technology. (More importantly, servlet
developers get paid more than Perl programmers :-).

 Efficient. With traditional CGI, a new process is started for the each HTTP request. If the
CGI program does a relatively fast operation, the overhead of starting the process can
dominate the execution of time. With servlets, the Java Virtual Machine stays up, and each
request is handled by a lightweight Java thread, not the heavyweight operating system
process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI
program, then the for the CGI program is loaded into memory N time. With servlets,
however, there are N threads but only a single copy of the servlets class. Servlets also have
more alternatives than do regular CGI programs for optimizations such as caching previous
computations, keeping the database connections open, and the like.

 Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of
being able to use a familiar language, servlets have an extensive infrastructure for
automatically parsing and decoding the HTML form data, reading and setting HTTP
headers, handling cookies, tracking sessions, and many other such utilities.

 Powerful. Java servlets let you easily do several things that are difficult or impossible with
the regular CGI. For one thing, servlets can talk directly to Web server (regular CGI
programs can't). This simplifies operations that need to look up images and other data
stored in the standard places. Servlets can also share data among each other, making the
useful things like database connection pools easy to implement. They can also maintain
information from request to request, simplifying things like session tracking and caching of
previous computation.

 Portable. Servlets are written in Java and followsss a well-standardized API.


Consequently, servlets written for, say I-Planet Enterprise Server can alsp run virtually
unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a
plugin on the almost every major Web server.

2
 Inexpensive. There are also a number of free or very inexpensive Web servers available
that are good for "personal" use or low-volume Web sites. However, with major exception
of Apache, which is free, most commercial-quality Web servers are relatively expensive.
Nevertheless, once you have a Web server, no matter the cost of that server, adding servlets
support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.

Advantages of servlets over CGI processes

Servlets:

 have significantly less overhead than CGI


 can inherit processing state between invocation
 can use concurrency control in the Java to share state at server.
Servlets compared to CGI programs:
 are slower only when being initially it is loaded
 rather faster to run when it is loaded.
Servlets can:
 open a database connection when initially it is loaded
 share open DB connection with successive invocation
 CGI programs have to renew the DB connection each time they're run.
Servlets can:
 store state information in the static variables in servlet
 share access to the state data each time servlet is run
 control concurrent access to the shared state easily
 CGI programs lack the common address space to share state easily.
Disadvantages of servlets over CGI processes
 cruder model of concurrency
 less robust - share common address space in the JVM process
 more complex to handle, write and configure
What You Should Already Know

Before you goes to this tutorial you should have a basic understanding of the following:

 HTML
 A basic understanding of JAVA
3
Life Cycle of Servlets

Servlets Life Cycle have the following Components:

 Handled by the servlets container.


 Create and initialize the servlets.
 Handle zero or more service call.
 Destroy and garbage collect the servlets.
 A single servlets instance to handle every request

The Basic Servlet Architecture or Life Cycle

Servlet container create only one instance of each servlet but the request of each user is handled
with a separate thread. Each thread then calls the doGet or doPost methods. This idea is shown in
the above Figure-5.

1.The init method of the servlets is called when the servlets is first created and each time the server
receives a request for a servlets, the server spawns a new thread calls service method.

2.The service method check the HTTP request type (GET,SET, PUT, DELETE, etc.) and calls
doGet, doPost, doPut,doDelete, etc. method as appropriate.

3.Finally, the server may decide to remove a previous loaded servlet. In this case, the server calls
destroy method of the servlets.

4
HTTP

Before we can start writing the first Servlets, we need to know some basics of HTTP ("HyperText
Transfer Protocol"), the protocol which is used by a WWW client (e.g. a browser) to send a request
to a Web Server.

HTTP is the request-response oriented protocol. An HTTP request consist of a request method, a
URI, header fields and a body (which can be empty). An HTTP response contain a result and again
header fields and a body.

The service method of HttpServlet dispatch a request to different Java methods for different HTTP
request methods. It recognize the standard HTTP/1.1 methods and should not be overridden in
subclasses unless you need to implement additional methods. The recognized methods are GET,
PUT,HEAD, POST, DELETE, OPTIONS and TRACE. Other methods are answered with a Bad
Request HTTP error. An HTTP method XXX is dispatched to the Java method doXxx, e.g. GET ->
doGet. All these method expect the parameters "(HttpServletRequest req, HttpServletResponse
res)". The method doOptions and doTrace have suitable default implementations and are usually
not overridden. The HEAD method (which is supposed to return the same header lines that a GET
method would return, but doesn't include a body) is performed by calling the doGet and ignoring
any output that is written by this method. That leaves us with the method doGet doPut doPost and
doDelete whose default implementations in HttpServlet return a Bad Request HTTP error. A
subclass of HttpServlet overrides one or more of these method to provide a meaningful
implementation.

The request data is passed to all the methods through the first argument of type HttpServletRequest
(which is a subclass of the more general ServletRequest class). The response can be created with
the methods of the second argument of type HttpServletResponse (a subclass of ServletResponse).

When you request a URL in the Web Browser, the GET method is used for the request. A GET
request does not have the body (i.e. the body is empty). The response should contain the body with
the response data and header fields which describe the body (especially Content-Type and Content-
Encoding). When you send an HTML form, either GET or POST action can be used. With the GET
request the parameters are end in the URL, with a POST request they are transmited in the body.
HTML editors and upload tools use PUT requests to the upload resources to a Web Server and
DELETE requests to delete resources.

5
Servlet Types
 Classic Servlets-service() Method
 JSP's-Java Embeded in HTML Templates
 Http Servlets-doGet & doPost()
 Visual Servlets-Generated by Visual Age
Packages in Servlets
There are two types of package available in servlets which are as follows:
1.javax.servlet.* 2.javax.servlet.http.*
Interfaces in javax.servlet.*
 RequestDispatcher
 Servlet
 ServletRequest
 ServletResponse
 ServletConfig
 ServletContext
 SingleThreadModel
Classes in javax.servlet.*
 GenericServlet
 ServletInputStream
 ServletOutputStream
 ServletException
 UnavailableException
Interfaces in javax.servlet.http.*
 HttpServletRequest
 HttpServletResponse
 HttpSessionBindingListener
 HttpSessionContext
 HttpSession
classes in javax.servlet.http.*
 Cookie
 HttpServlet
 HttpUtils

6
 HttpSessionBindingEvent
Servlet Scope Objects
The <minOccurs> indicator specify the minimum number of time an element can occur:

There are four scope objects in servlets which enables the sharing information between web
components. The scope objects and their corresponding Java classes are listed below:

 Web Context javax.servlet.ServletContext


 Request javax.servlet.HttpServletRequest
 Session javax.servlet.http.HttpSession
 Page javax.servlet.jsp.PageContext

You can get the attribute values from servlet scope objects using getAttribute method and set new
values of attributes using setAttribute method. For example, you can get the client’s IP address by
calling the getRemoteAddr method of HttpServletRequest class.

Following Examples prints the Hello World in the browser

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet


{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}

To be a servlet, a class should extend the HttpServlet and override doGet or doPost (or both),
depending on whether the data is being sent by GET or by POST. These methods take two

7
arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has
methods that let you find out about the incoming information such as FORM data, HTTP request
headers, and the like.

The HttpServletResponse has method that lets you specify the HTTP response line (200, 404, etc.),
response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a
PrintWriter used to send output back to the client. For simple servlet, most of the effort is spent in
println statements that generate the desired page. Note that doGet and doPost throw two exception,
so you are required to include them in the declaration. Also note that you have to import classes in
the java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for
HttpServletRequest and HttpServletResponse). Finally, note that doGet and doPost are called by
service method, and sometimes you may want to override service directly, e.g. for a servlet that
handles both GET and POST request.

Compiling and Installing the Servlet

Note that the specific details for installing servlet vary from Web server to Web server. Please refer
to your Web server documentation for the definitive directions. The on-line examples are running
on Java Web Server (JWS) 2.0, where servlet are expected to be in a directory called servlets in the
JWS installation hierarchy. However, I placed this servlets in a separate package (hall) to avoid
conflicts with other servlets on this server; you'll want to do the same if you are using a Web server
that is used by other people and doesn't have a good infrastructure for the "virtual servers" to
prevent these conflicts automatically. Thus, HelloWorld.java actually goes in a subdirectory called
hall in the servlets directory.

Note that setup on most other servers is similar, and the servlets and JSP examples in the tutorial
have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent
mechanism for virtual servers, and it is not necessary to use packages solely to prevent name
conflicts with other users.

If you've never used the packages before, there are two main ways to compile classes that are in
packages.

One way is to set your CLASSPATH to point to directory above the one actually containing your
servlets. You can them compile normally from within the directory. For example, if your base
directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory name) is the
8
hall, and you were on Windows, you'd do:

DOS> set CLASSPATH=C:\JavaWebServer\servlets;%CLASSPATH%


DOS> cd C:\JavaWebServer\servlets\hall
DOS> javac YourServlet.java

The first part, setting CLASSPATH, you probably want to do permanently, rather than each time
you start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH=..."
statement in your autoexec.bat file somewhere after the line that set CLASSPATH to point to
servlet.jar and jsp.jar. On Windows NT, you'd go to Start menu, select Settings, select Control
Panel, select System, select Environment, then enter the variable and value. Note also that if your
package were of the form name1.name2.name3 rather than simply name1 as here, you'd still have
the CLASSPATH point to the top-level directory of your package hierarchy (the one containing
name1).

A second way to compile classes that are in packages is to go to directory above the one containing
your servlets, and then do "javac directory\YourServlet.java" (Windows; note the backslash) or
"javac directory/YourServlet.java" (Unix; note the forward slash). For example, suppose again that
your base directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory
name) is hall, and you were on Windows. In that case, you'd do following:

DOS> cd C:\JavaWebServer\servlets
DOS> javac hall\YourServlet.java

Note that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash,
after directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use
the JDK 1.1, many servlet authors stick with JDK 1.1 for portability.

Finally, another advanced option is to keep source code in a location distinct from the .class files,
and use javac's "-d" option to install them in the location the Web server expects.

Running the Servlet


With the Java Web Server, servlet are placed in the servlets directory within the main JWS
installation directory, and are invoked via http://host/servlet/ServletName. Note that the directory
is servlets plural, while URL refers to servlet, singular. Since this example was placed in the hall
9
package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may have
slightly different conventions on where to install servlets and how to invoke them. Most server also
let you define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any-
file.html. The process for doing this is completely server-specific; check your server's
documentation for the details.

A Servlet that Generates HTML


Most servlet generate HTML, not plain text as in the previous example. To do that, you need two
additional steps: tell the browser that you're sending back HTML, and modify the println
statements to build a legal Web page. The first step is done by setting Content-Type response
header. In general, headers can be set via the setHeader method of HttpServletResponse, but
setting the content type is such a common task that there is also a special setContentType method
just for this purpose. Note that you need to set the response headers before actually returning any
of the content via the PrintWriter. Here's an example:
The following program called HelloWWW.java will print Hellow WWW in the browser in the
HTML format.

package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWWW extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" +
"<HTML>\n" +
"<HEAD><TITLE&ht;Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
10
"<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
}
}
Output:

Handling the Client Request:Form Data

 When the user submits form, his information is sent to the corresponding servlet file
because we've set the ACTION attribute to point to the servlet.
 The form can use the GET method or POST method.

 In GET method, if the user enter the name "Inigo Montoya," the request URL is
http://server:8080/servlet/Hello?name=Inigo+Montoya in the form of querystring which is
visible to the user.

 The space in the name is specially encoded as a plus sign by the browser because URLs
cannot contain space.

 A servlet's HttpServletRequest object gives it access to form data in its query string.

Difference between GET and POST Method

When the user enters information in a form and clicks Submit , there are two ways the information
can be sent from browser to server: in the URL, or within the body of the HTTP request.

11
The GET method, which was used in example earlier, appends name/value pairs to the URL.
Unfortunately, the length of URL is limited, so this method only works if there are only a few
parameters. The URL could be truncated if the form uses a large number of parameter or if the
parameters contain large amounts of data. Also, parameters passed on URL are visible in the
address field of the browsernot the best place for a password to be displayed.

The alternative to the GET method is POST method. This method packages the name/value pairs
inside the body of HTTP request, which makes for a cleaner URL and imposes no size limitation
on the forms output. It is more secure.

Overriding service, doGet, and doPost

When a request is made, Servlet Engine hands on the incoming data to the Servlet engine, which
processes the request, including form data, cookies, session information, and URL name-value
pairs, into an object of type HttpServletRequest called the request object. Client metadata is
encapsulated as the object of type HttpServletResponse and is called the response object. The
Servlet engine passes both objects as parameters to Servlets service() method.

The default service() method in an HTTP servlets routes the request to another method based on
the HTTP transfer method (POST, GET, etc.) For example, HTTP POST requests are routed to
doPost() method, HTTP GET requests are routed to the doGet() method, and so on. This enables
the Servlet to perform different processing on request data depending on the transfer method. Since
routing takes place in service(), you generally do not override service() in an HTTP Servlet.
Instead, override doGet() and/or doPost(), etc., depending on type of request you expect.

The automatic routing in an HTTP Servlets is based simply on a call to request.getMethod(), which
provides the HTTP transfer method. In Servlets Engine, request data is already preprocessed into a
name-value list by the time the Servlet sees the data, so you could simply override the service()
method in an HTTP Servlet without losing any functionality. However, this does make the Servlet
less portable, since it is now dependent on preprocessed request data.

You must override service() method (for generic Servlets) or the doGet() and/or doPost() methods
(for HTTP servlets) to perform the tasks needed to answer the request. Very often, this means
accessing EJBs to perform the business transactions, collating the needed information (in the
request object or in a JDBC ResultSet object), and then passing the newly generated content to the
JSP for formatting and delivery back to the client.
12
Most operations that involve the forms use either a GET or a POST operation, so for most servlets
you override either doGet() or doPost(). Note that you can implement both the methods to provide
for both types of input, or simply pass the request object to a central processing method
Syntax of Using doGet
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
...servlet code goes here...
}
Syntax of Using doPost
public void doPost (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
...servlet code goes here...
}

All of the actual request-by-request traffic in an HTTP Servlets is handled in the appropriate
doOperation() method, including session management, user authentication, dispatching EJBs and
JSPs, and accessing iAS features.

If you have a Servlets that you intend to also call using a RequestDispatcher method include() or
forward() , be aware that the request information is no longer sent as HTTP POST, GET, etc.
RequestDispatcher methods always call the service(). In other words, if a servlet overrides
doPost(), it may not process anything if another servlet calls it, if the calling servlet happens to
have received its data via HTTP GET. For this reason, be sure to implement routines for all
possible types of the input, as explained above.

Note Arbitrary binary data, like uploaded files or images, can be problematic, since web connector
translates incoming data into name-value pairs by default. You can program web connector to
properly handle this kind of data and package it correctly in the request object. Accessing
Parameters and Storing the Data

Incoming data is encapsulated in the request object. For HTTP servlet, the request object is of type
HttpServletRequest. For generic servlet, the request object is of type ServletRequest. The request

13
object contains all the parameters in a request, and you can also set your own values in the request.
The latter is called attribute.

You can access all the parameters in an incoming request by using getParameter() method.

The following example describe the use of getParameter()


String username = request.getParameter("accountNumber");
You can also set and retrieve values in the request object using setAttribute() and getAttribute(),
respectively.
The following example describe the use of setAttribute()
request.setAttribute("accountNumber", "3284766");
A complete example showing the use of doGet Method in Servlets
Step1:Make the HTML form
Step2:Make the corresponding Servlets Page

Step1:Make the HTML form


Here we are make a HTML form called form.html which is given below:
<html>
<head>
<title>Introductions</title>
</head>
<body>
<form method=GET action="/servlet/name">
If you don't mind me asking, what is your name?
<input type=text name="name"><P>
<input type=submit>
</form>
</body>
</html>

Step2:Make the corresponding Servlets Page


Here we are make a Servlets filr called name.java as we have given in the action attribute path in
the form.html as name which is given below:

14
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class name extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

String name = req.getParameter("name");


out.println("<html>");
out.println("<head><title>Hello, " + name + "</title></head>");
out.println("<body>");
out.println("Hello, " + name);
out.println("</body></html>");
}
public String getServletInfo()
{
return "A servlet that knows the name of the person to whom it's" + "saying hello";
}
}

Handling the Client Request: HTTP Request Headers

 When the HTTP client (e.g. a browser) sends a request, it is required to supply a request
line (usually GET or POST).
 If it wants to, it can also send the number of headers, all of which are optional except for
Content-Length, which is required only for POST requests

15
HTTP Request Header Methods Available in Servlets

General:
-getHeader (header name is not case sensitive)
-getHeaderNames
-getHeaders
Specialized
-getCookies
-getAuthType and getRemoteUser
-getContentLength
-getContentType
-getMethod
-getRequestURI
-getQueryString
-getDateHeader
-getIntHeader
-Related info
-getProtocol

An Overview of Request Headers

When the HTTP client (e.g. a browser) sends a request, it is required to supply a request line
(usually GET or POST). If it wants to, it can also send the number of headers, all of which are
optional except for Content-Length, which is required only for POST requests. Here are the most
common headers:

 Accept The MIME types that the browser prefers.


 Accept-Charset The character set that the browser expects.
 Accept-Encoding The types of data encodings (such as gzip) that the browser knows how
to decode. Servlet can explicitly check for gzip support and return gzipped HTML pages to
browsers that support them, setting the Content-Encoding response header to indicate that
they are gzipped. In many cases, this can reduce page download times by a factor of five or
ten.

 Accept-Language The language the browser is expecting, in case the server has versions in
more than the one language.
16
 Authorization Authorization info, usually in response to the WWW-Authenticate header
from the server.

 Connection Use persistent connection? If a servlet get a Keep-Alive value here, or gets a
request line indicating HTTP 1.1 (where persistent connections are the default), it may be
able to take advantage of persistent connections, saving significant time for Web pages that
include several small pieces (images or applet classes). To do this, it needs to send the
Content-Length header in the response, which is most easily accomplished by writing into
a ByteArrayOutputStream, then looking up the size just before writing it out.

 Content-Length (for POST messages, how much the data is attached)

 Cookie (one of most important headers; see separate section in this tutorial on handling
cookies)

 From (email address of the requester; only used by Web spiders and other custom clients,
not by browsers)

 Host (host and the port as listed in the original URL)


 If-Modified-Since (only return documents newer than this, otherwise send the 304 "Not
Modified" response)

 Pragma (the no-cache value indicates that the server should return the fresh document, even
if it is a proxy with a local copy)

 Referer (the URL of the page containing the link the user followed to get to the current
page)

 User-Agent (type of the browser, useful if servlet is returning browser-specific content)

UA-Pixels, UA-Color, UA-OS, UA-CPU (nonstandard header sent by some Internet Explorer
versions, indicating screen size, color depth, operating system, and cpu type used by the browser's
system)

Reading Request Headers from Servlets

17
Reading headers is the very straightforward; just call the getHeader method of the
HttpServletRequest, which returns a String if the header was supplied on this request, null
otherwise. However, there are the couple of headers that are so commonly used that they have
special access methods. The getCookies method returns contents of the Cookie header, parsed and
stored in an array of Cookie objects. See the separate section of this tutorial on cookies. The
getAuthType and getRemoteUser methods break Authorization header into its component pieces.
The getDateHeader and getIntHeader methods read the specified header and then convert them to
Date and int values, respectively.

Rather than looking up one of the particular header, you can use the getHeaderNames to get an
Enumeration of all header names received on this particular request.

Finally, in addition to looking up request headers, you can get information on the main request line
itself. The getMethod method returns the main request method (normally GET or POST, but things
like HEAD, PUT, and DELETE are possible). The getRequestURI method returns URI (the part of
the URL that came after the host and port, but before the form data). The getRequestProtocol
returns third part of the request line, which is generally "HTTP/1.0" or "HTTP/1.1".
The following example called showHeaders.java prints all the headers in the browser
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class ShowRequestHeaders extends HttpServlet


{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
out.println(ServletUtilities.headWithTitle(title) +
"<body bgcolor=\"#FDF5E6\">\n" +
"<h1 align=center>" + title + "</h1>\n" +
18
"<b>Request Method: </b>" +
request.getMethod() + "&ltbr>\n" +
"<b>Request URI: </b>" +
request.getRequestURI() + "<BR>\n" +
"<b>Request Protocol: </b>" +
request.getProtocol() + "<BR><BR>\n" +
"<table border=1 align="center">\n" +
"<tr bgcolor=\"#FFAD00\">\n" +
"<th>Header Name<th>Header Value");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements())
{
String headerName = (String)headerNames.nextElement();
out.println("<tr><td>" + headerName);
out.println(" <td>" + request.getHeader(headerName));
}
out.println("</table>\n</body></html>");
}

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}

Accessing the Standard CGI Variables

To build the successful web application, you often need to know a lot about the environment in
which it is running.
You may need to find out about server that is executing your servlets or the specifics of the client
that is sending requests. And no matter what kind of environment the application is running in, you
most certainly need the information about the requests that the application
is handling.
19
Advantages of Using Servlets Over CGI
 Stronger type checking. In other words, more help from compiler in catching errors. A CGI
program uses one function to retrieve its environment variable. Many errors cannot be
found until they cause runtime problem. Let's look at how both a CGI program and servlets
find the port on which its server is running.

A CGI script written in Perl call: $port = $ENV{'SERVER_PORT'}; port is an untyped


variable. A CGI program written in C call: The chance for accidental errors is also high.
The environment variable name could be misspelled or the data type might not match what
the environment variable returns.

A servlet, on the other hand, call:

int port = req.getServerPort()

This eliminates a lot of the accidental errors because the compiler can guarantee there are
no misspellings and each return type is as it should be.

 Delayed calculation. When the server launches a CGI program, the value for each and
every environment variable must be precalculated and passed, whether the CGI program
uses it or not. A server launching the servlets has the option to improve performance by
delaying these calculations and performing them on demand as needed.

More interaction with server. Once the CGI program begins execution, it is untethered from its
server. The only communication path available to program is its standard output. A servlet,
however, can also work with the server. As discussed in the last chapter, a servlet operates either
within the server (when possible) or as connected process outside the server (when necessary).
Using this connectivity, a servlet can make ad hoc requests for calculated the information that only
the server can provide. For example, a servlet can have its server do arbitrary path translation,
taking into consideration the server's aliases and virtual paths.
CGI Environment Variables and the Corresponding Servlet Methods

CGI Environment Variable HTTP Servlet Method


SERVER_NAME req.getServerName()
SERVER_SOFTWARE getServletContext().getServerInfo()

20
SERVER_PROTOCOL req.getProtocol()
SERVER_PORT req.getServerPort()
REQUEST_METHOD req.getMethod()
PATH_INFO req.getPathInfo()
PATH_TRANSLATED req.getPathTranslated()
SCRIPT_NAME req.getServletPath()
DOCUMENT_ROOT req.getRealPath("/")
QUERY_STRING req.getQueryString()
REMOTE_HOST req.getRemoteHost()
REMOTE_ADDR req.getRemoteAddr()
AUTH_TYPE req.getAuthType()
REMOTE_USER req.getRemoteUser()
CONTENT_TYPE req.getContentType()
CONTENT_LENGTH req.getContentLength()
HTTP_ACCEPT req.getHeader("Accept")
HTTP_USER_AGENT req.getHeader("User-Agent")
HTTP_REFERER req.getHeader("Referer")

The following example reading all the CGI variables


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

/** Creates a table showing the values of all the CGI variables.
* * Part of tutorial on servlets and JSP that appears at
* 1999 Marty Hall; may be freely used or adapted.
*/
public class ShowCGIVariables extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException

21
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String[][] variables =
{
{ "AUTH_TYPE", request.getAuthType() },
{ "CONTENT_LENGTH", String.valueOf(request.getContentLength()) },
{ "CONTENT_TYPE", request.getContentType() },
{ "DOCUMENT_ROOT", getServletContext().getRealPath("/") },
{ "PATH_INFO", request.getPathInfo() },
{ "PATH_TRANSLATED", request.getPathTranslated() },
{ "QUERY_STRING", request.getQueryString() },
{ "REMOTE_ADDR", request.getRemoteAddr() },
{ "REMOTE_HOST", request.getRemoteHost() },
{ "REMOTE_USER", request.getRemoteUser() },
{ "REQUEST_METHOD", request.getMethod() },
{ "SCRIPT_NAME", request.getServletPath() },
{ "SERVER_NAME", request.getServerName() },
{ "SERVER_PORT", String.valueOf(request.getServerPort()) },
{ "SERVER_PROTOCOL", request.getProtocol() },
{ "SERVER_SOFTWARE", getServletContext().getServerInfo() }

}; String title = "Servlet Example: Showing CGI Variables";


out.println(ServletUtilities.headWithTitle(title) +
"<body bgcolor=\"#FDF5E6\">\n" +
"<h1 align="center"> + title + "</h1>\n" +
"<table boder=1 align="center"\n" +
"<tr bgcolor=\"#FFAD00\">\n" +
"<th>CGI Variable Name<h1>Value");
for(int i=0; i
{
String varName = variables[i][0];
String varValue = variables[i][1];
if (varValue == null)
22
varValue = "Not specified";
out.println("<tr><td>" + varName + "<td>" + varValue);
}
out.println("</table></body></html>");
}

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Generating the Server Response: HTTP Status Codes
When a Web server responds to the request from the browser or other Web client, the response
typically consists of a status line, some response headers, a blank line, and the document
Specifying Status Codes

As described above, the HTTP response status line consists of the HTTP version, a status code, and
an associated message. Since the message is directly associated with the status code and the HTTP
version is determined by the server, all the servlet needs to do is to set status code. The way to do
that is by the setStatus method of the HttpServletResponse.

The setStatus method takes the int (the status code) as an argument, but instead of using explicit
numbers, it is clearer and more reliable to use the constants defined in HttpServletResponse. The
name of each constant is derived from standard HTTP 1.1 message for each constant, all uppercase
with a prefix of SC(for Status Code) and spaces changed to underscores. Thus, since the message
for 404 is Not Found, the equivalent constant in the HttpServletResponse is SC_NOT_FOUND
There are two exceptions however. For some odd reason the constant for code 302 is derived from
the HTTP 1.0 message, not the HTTP 1.1 message, and the constant for the code 307 is missing
altogether.

Setting the status code does not always mean that you don't need to the return a document. For
example, although most servers will generate the small "File Not Found" message for 404
responses, a servlets might want to customize this response. However, if you do this, you need to
be sure to call response.setStatus before sending any content via PrintWriter.
23
Although the general method of setting status codes is simply to the call response.setStatus(int),
there are two common cases where a shortcut method in the HttpServletResponse is provided. The
sendError method generates the 404 response along with a short message formatted inside an
HTML document. And the sendRedirect method generates the 302 response along with a Location
header indicating the URL of the new document.
HTTP 1.1 Status Codes and Their Meaning
Following is the list of all the available HTTP 1.1 status codes, along with their associated message
and interpretation. You should be cautious in using status codes that are available only in HTTP
1.1, since many browsers still only support HTTP 1.0. If you do use the status codes specific to
HTTP 1.1, in most cases you want to either explicitly check the HTTP version of request (via the
getProtocol method of the HttpServletRequest) or reserve it for situations when no HTTP 1.0
status code would be particularly meaningful to the client anyhow.

Status Associated
Meaning
Code Message
100 Continue Continue with partial request. (New in HTTP 1.1)

Switching
101 Server will comply with Upgrade header and change to different
Protocols
protocol. (New in HTTP 1.1)

200 OK Everything's fine; document follows for GET and POST requests. This is
the default for servlets; if you don't use setStatus, you'll get this.

201 Created
Server created a document; the Location header indicates its URL.
202 Accepted Request is being acted upon, but processing is not completed.
Non- Document is being returned normally, but some of the response headers
203 Authoritative might be incorrect since a document copy is being used. (New in HTTP
Information 1.1)
204 No Content
No new document; browser should continue to display previous
document. This is a useful if the user periodically reloads a page and you
can determine that the previous page is already up to date. However, this
does not work for pages that are automatically reloaded via the Refresh
response header or the equivalent <META HTTP-EQUIV="Refresh" ...>
header, since returning this status code stops future reloading.
JavaScript-based automatic reloading could still work in such a case,
24
though.

205 Reset Content No new document, but browser should reset document view. Used to
force browser to clear CGI form fields. (New in HTTP 1.1)

206 Partial Content Client sent a partial request with a Range header, and server has fulfilled
it. (New in HTTP 1.1)

Multiple Document requested can be found several places; they'll be listed in the
300
Choices returned document. If server has a preferred choice, it should be listed in
the Location response header.

Moved Requested document is elsewhere, and the URL for it is given in the
301
Permanently Location response header. Browsers should automatically follow the link
to the new URL.
302 Found Similar to 301, except that the new URL should be interpreted as a
temporary replacement, not a permanent one. Note: the message was
"Moved Temporarily" in HTTP 1.0, and the constant in
HttpServletResponse is SC_MOVED_TEMPORARILY, not
SC_FOUND.Very useful header, since browsers automatically follow
the link to the new URL. This status code is so useful that there is a
special method for it, sendRedirect. Using response.sendRedirect(url)
has a couple of advantages over doing
response.setStatus(response.SC_MOVED_TEMPORARILY) and
response.setHeader("Location", url). First, it is easier. Second, with
sendRedirect, the servlet automatically builds a page containing the link
(to show to older browsers that don't automatically follow redirects).
Finally, sendRedirect can handle relative URLs, automatically
translating them to absolute ones.

Note that this status code is sometimes used interchangeably with 301.
some servers will send 301 and others will send 302.

Technically, browsers are only supposed to automatically follow the


redirection if the original request was GET. See the 307 header for
25
details.

Like 301/302, except that if the original request was POST, the
303 See Other
redirected document (given in the Location header) should be retrieved
via GET. (New in HTTP 1.1)

Client has a cached document and performed a conditional request

304 Not Modified (usually by supplying an If-Modified-Since header indicating that it only
wants documents newer than a specified date). Server wants to tell client
that the old, cached document should still be used.

305 Use Proxy Requested document should be retrieved via proxy listed in Location
header. (New in HTTP 1.1)

This is identical to 302 ("Found" or "Temporarily Moved"). It was added


to HTTP 1.1 since many browsers erroneously followed the redirection
on a 302 response even if the original message was a POST, even though
it really ought to have followed the redirection of a POST request only
Temporary
307 on a 303 response. This response is intended to be unambigously clear:
Redirect
follow redirected GET and POST requests in the case of 303 responses,
only follow the redirection for GET requests in the case of 307
responses. Note: for some reason there is no constant in
HttpServletResponse corresponding to this status code. (New in HTTP
1.1)
400 Bad Request Bad syntax in the request.

Client tried to access password-protected page without proper

401 Unauthorized authorization. Response should include a WWW-Authenticate header


that the browser would use to pop up a username/password dialog box,
which then comes back via the Authorization header.

403 Forbidden Resource is not available, regardless of authorization. Often the result of
bad file or directory permissions on the server.
404 Not Found
No resource could be found at that address. This is the standard "no such

26
page" response. This is such a common and useful response that
there is a special method for it in HttpServletResponse:
sendError(message). The advantage of sendError over setStatus is that,
with sendError, the server automatically generates an error page showing
the error message.
Method Not The request method (GET, POST, HEAD, DELETE, PUT, TRACE, etc.)
405
Allowed was not allowed for this particular resource. (New in HTTP 1.1)

406 Not Acceptable Resource indicated generates a MIME type incompatible with that
specified by the client via its Accept header. (New in HTTP 1.1)
Proxy
Similar to 401, but proxy server must return a Proxy-Authenticate
407 Authentication
header. (New in HTTP 1.1)
Required
Request
408 The client took too long to send the request. (New in HTTP 1.1)
Timeout

409 Conflict Usually associated with PUT requests; used for situations such as trying
to upload an incorrect version of a file. (New in HTTP 1.1)

Document is gone; no forwarding address known. Differs from 404 in


410 Gone
that the document is is known to be permanently gone in this case, not
just unavailable for unknown reasons as with 404. (New in HTTP 1.1)

Length
411 Server cannot process request unless client sends a Content-Length
Required
header. (New in HTTP 1.1)

Precondition
412 Some precondition specified in the request headers was false. (New in
Failed
HTTP 1.1)

Request Entity The requested document is bigger than the server wants to handle now.
413
Too Large If the server thinks it can handle it later, it should include a Retry-After
header. (New in HTTP 1.1)
Request URI
414 The URI is too long. (New in HTTP 1.1)
Too Long

27
Unsupported
415 Request is in an unknown format. (New in HTTP 1.1)
Media Type
Requested
Client included an unsatisfiable Range header in request. (New in HTTP
416 Range Not
1.1)
Satisfiable
Expectation
417
Failed Value in the Expect request header could not be met. (New in HTTP 1.1)

Internal Server Generic "server is confused" message. It is often the result of CGI
500
Error programs or (heaven forbid!) servlets that crash or return improperly
formatted headers.

Not
501 Server doesn't support functionality to fulfill request. Used, for example,
Implemented
when client issues command like PUT that server doesn't support.

502 Bad Gateway Used by servers that act as proxies or gateways; indicates that initial
server got a bad response from the remote server.

Service Server cannot respond due to maintenance or overloading. For example,


503
Unavailable a servlet might return this header if some thread or database connection
pool is currently full. Server can supply a Retry-After header.

Gateway Used by servers that act as proxies or gateways; indicates that initial
504
Timeout server didn't get a response from the remote server in time. (New in
HTTP 1.1)

HTTP Version
505 Server doesn't support version of HTTP indicated in request line. (New
Not Supported
in HTTP 1.1)

Generating the Server Response: HTTP Response Headers

A response from the Web server normally consists of a status line, one or more response headers, a
blank line, and the document

28
Setting the HTTP response headers often goes hand in hand with the setting the status codes in the
status line. For example, several of the "document moved" status codes have an accompanying
Location header, and the 401 (Unauthorized) code must include an accompanying WWW-
Authenticate header.

Overview

The most general way to specify headers is by setHeader method of HttpServletResponse, which
takes two strings: the header name and the header value. Like setting the status codes, this must be
done before any document content is sent.

There are also two specialized methods to set the headers that contain dates (setDateHeader) and
integers (setIntHeader). The first saves you trouble of translating a Java date in milliseconds since
the epoch (as returned by System.currentTimeMillis or the getTime method applied to a Date
object) into a GMT time string. The second spares you the minor inconvenience of the converting
an int to a String.

Rather than setting the header outright, you can add a new header, in case a header with that name
already exists. Use addHeader, addDateHeader, and addIntHeader for this. If it really matters to
you whether a specific header has already been set, use containsHeader to check.

Finally, HttpServletResponse also supplies a number of convenience methods for the specifying
common headers.

 The setContentType method sets Content-Type header, and is used by the majority of
servlets.
 The setContentLength method sets Content-Length header, useful if the browser supports
persistent (keep-alive) HTTP connections.

 The addCookie method sets the cookie (there is no corresponding setCookie, since it is
normal to have multiple Set-Cookie lines).

 And, as discussed in the previous section, the sendRedirect method sets Location header as
well as setting the status code to 302.

Common Response Headers and their Meaning

29
Header Interpretation/Purpose
Allow What request methods (GET, POST, etc.) does the server support?

What method was used to encode the document? You need to decode it to get the
type specified by the Content-Type header. Using gzip to compress the document
can dramatically reduce download times for HTML files, but it is only supported
by Netscape on Unix and IE 4 and 5 on Windows. On the other hand, gzipping
Content-
HTML files can dramatically reduce download times, and Java's
Encoding
GZIPOutputStream makes it easy. So you should explicitly check if the browser
supports this by looking at the Accept-Encoding header (i.e. via
request.getHeader("Accept-Encoding")). That way, you can return gzipped pages
to browser that know how to unzip them, but still return regular pages to other
browsers.

How many bytes are being sent? This information is only needed if the browser is
using a persistent (keep-alive) HTTP connection. If you want your servlet to take
Content-
advantage of this when the browser supports it, your servlet should write the
Length
document into a ByteArrayOutputStream, look up its size when done, put that into
the Content-Length field, then send the content via
byteArrayStream.writeTo(response.getOutputStream()).

What is the MIME type of the following document? Default for servlets is
Content-
text/plain, but they usually explicitly specify text/html. Setting this header is so
Type
common that there is a special method in HttpServletResponse for it:
setContentType

Date What is current time (in GMT)? Use the setDateHeader method to specify this
header. That saves you the trouble of formatting the date string properly.

Expires
At what time should content be considered out of date and thus no longer cached?
Last-
When was document last changed? Client can supply a date via an If-Modified-
Modified
Since request header. This is treated as a conditional GET, with document only
being returned if the Last-Modified date is later than the specified date. Otherwise
a 304 (Not Modified) status line is returned. Again, use the setDateHeader method

30
to specify this header.

Location Where should client go to get document? This is usually set indirectly, along with
a 302 status code, via the sendRedirect method of HttpServletResponse.

How soon should browser ask for an updated page (in seconds)? Instead of just
reloading current page, you can specify a specific page to load via
setHeader("Refresh", "5; URL=http://host/path"). Note that this is commonly set
via <META HTTP-EQUIV="Refresh" CONTENT="5; URL=http://host/path"> in
the HEAD section of the HTML page, rather than as an explicit header from the
server. This is because automatic reloading or forwarding is something often
desired by HTML authors who do not have CGI or servlet access. But for servlets,
Refresh
setting the header directly is easier and clearer. Note that this header means
"reload this page or go to the specified URL in N seconds." It does not mean
"reload this page or go to the specified URL every N seconds." So you have to
send a Refresh header each time, and sending a 204 (No Content) status code stops
the browser from reloading further, regardless of whether you explicitly send the
Refresh header or use <META HTTP-EQUIV="Refresh" ...>. Note that this
header is not officially part of HTTP 1.1, but is an extension supported by both
Netscape and Internet Explorer.

Server
What server am I? Servlets don't usually set this; the Web server itself does.

Specifies cookie associated with page. Servlets should not use

Set-Cookie response.setHeader("Set-Cookie", ...), but instead use the special-purpose


addCookie method of HttpServletResponse. See separate section on handling
cookies.

What authorization type and realm should client supply in their Authorization
header? This header is required in responses that have a 401 (Unauthorized) status
WWW-
line. E.g. response.setHeader("WWW-Authenticate", "BASIC
Authenticate
realm=\"executives\""). Note that servlets do not usually handle this themselves,
but instead let password-protected Web pages be handled by the Web server's
specialized mechanisms (e.g. .htaccess).

31
Handling Cookies

Cookies are small bits of textual information that the Web server sends to the browser and that the
browser returns unchanged when visiting the same Web site or domain later

Advantages of using Cookies

By having the server read information it sent the client previously, the site can provide visitors
with the number of conveniences:

 Identifying the user during an e-commerce session. Many on-line stores use the
"shopping cart" metaphor in which the user selects an item, adds it to his shopping cart,
then continues shopping. Since HTTP connection is closed after each page is sent, when the
user select a new item for his cart, how does the store know that he is the same user that put
the previous item in his cart? Cookies are the good way of accomplishing this. In fact, this
is so useful that servlet have an API specifically for this, and servlet authors don't need to
manipulate cookies directly to make use of it.
 Avoiding username and password. Many large sites require you to register in order to use
their service, but it is inconvenient to remember the username and password. Cookies are
the good alternative for low-security sites. When a user registers, a cookie is sent with a
unique user ID. When the client reconnects at the later date, the user ID is returned, the
server looks it up, determines it belongs to the registered user, and doesn't require an
explicit username and password.

 Customizing a site. Many "portal" sites let you customize the look of main page. They use
cookies to remember what you wanted, so that you get that result initially for the next time.
I'll give an example like this later in this section of the tutorial.

 Focusing advertising. The search engine charge their customers much more for displaying
"directed" ads than "random" ads. That is, if you do a search on "Java Servlets", a search
site can charge much more for an ad for the servlets development environment than an ad
for an on-line travel agent. On the other hand, if the search had been "Bali Hotels", the
situation would be the reversed. The problem is that they have to show a random ad when
you first arrive and haven't yet performed the search, as well as when you search on
something that doesn't match any ad categories. Cookies let them remember "Oh, that's the

32
person who was searching for such and such previously" and displays an appropriate (read
"high priced") ad instead of a random (read "cheap") one.

Creating Cookies
A Cookie is created by calling Cookie constructor, which takes two string: the cookie name and the
cookie value
The following example describes how to create a cookie
Cookie userCookie = new Cookie("user", "uid1234"); response.addCookie(userCookie);

Getting the Value of a Cookie with a Specified Name


The following example called cookie.java that slightly simplify the retrieval of a cookie value
given a cookie name by looping through the array of available Cookie objects, returning the value
of any Cookie whose name matches the input. If there is no match, the designated default value is
returned. :
public static String getCookieValue(Cookie[] cookies,
String cookieName,
String defaultValue)
{
for(int i=0; i
{
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}

Session Tracking

HTTP is the stateless protocol: it provides no way for the server to recognize that a sequence of
requests are all from the same client.

 Privacy advocates may consider this the feature, but it causes problems because many web
applications aren't stateless

What is Session Tracking?


33
There are a number of problems that arise from the fact that HTTP is the "stateless" protocol. In
particular, when you are doing the on-line shopping, it is a real annoyance that the Web server can't
easily remember previous transactions. This makes the applications like shopping carts very
problematic: when you add an entry to your cart, how does the server know what's already in your
cart? Even if servers did retain contextual information, you'd still have the problems with e-
commerce. When you move from the page where you specify what you want to buy (hosted on the
regular Web server) to the page that takes your credit card number and shipping address (hosted on
the secure server that uses SSL), how does the server remember what you were buying?

Methods to Track the Session


There are four types of techniques used in servlet to handle the session which are as follows:
1.URL Rewritting
2.Hidden Form Fieds
3.Http Session
4.Secure Socket Layer(SSL)
1.URL Rewritting
You can append some extra data on the end of the each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session only. This is
also an excellent solution, and even has advantage that it works with the browsers that don't
support cookies or where the user has disabled cookies. However, it has most of same problems as
cookies, namely that the server-side program has a lot of straightforward but tedious processing to
do. In addition, you have to be very careful that every URL returned to user (even via indirect
means like Location fields in server redirects) has the extra information appended. And, if the user
leaves session and comes back via a bookmark or link, the session information can be lost.
2.Hidden Form Fieds
HTML forms have an entry that looks like following: <input type="hidden" name="session"
value="...">. This means that, when the form is submitted, the specified name and value are
included in GET or POST data. This can be used to store information about the session. However,
it has the major disadvantage that it only works if every page is dynamically generated, since the
whole point is that each session has the unique identifier.
3.Http Session

The HttpSession interface is implemented by the services to provide an association between an


HTTP client and HTTP server. This association, or session, persists over multiple connection

34
and/or requests during a given time period. Sessions are used to maintain the state and user identity
across multiple page requests.

A session can be maintained either by using the cookies or by URL rewriting. To expose whether
the client supports cookies, HttpSession defines the isCookieSupportDetermined method and an
isUsingCookies method.

HttpSession defines the methods which store these types of data:

 Standard session properties, such as an identifier for the session, and the context for the
session.
 Application layer data, accessed using this interface and stored using the dictionary-like
interface.

The following code snippet illustrate getting and setting the the session data value.

//Get the session object - "request" represents the HTTP servlet request
HttpSession session = request.getSession(true);

//Get the session data value - an Integer object is read from


//the session, incremented, then written back to the session.
//sessiontest.counter identifies values in the session
Integer ival = (Integer) session.getValue("sessiontest.counter");
if (ival==null)
ival = new Integer(1);
else
ival = new Integer(ival.intValue() + 1);
session.putValue("sessiontest.counter", ival);

4.Secure Socket Layer(SSL)

The Secure Sockets Layer protocol, or SSL, sits between application-level protocol (in this case
HTTP) and the low-level transport protocol (for the Internet, almost exclusively TCP/IP). It
handles the details of the security management using public key cryptography to encrypt all
client/server communication. SSL was introduced by Netscape with Netscape Navigator 1. It has
since become the de facto standard for the secure online communications and forms the basis of he

35
Transport Layer Security (TLS) protocol currently under development by the Internet Engineering
Task Force.

SSL Version 2.0, the version first to gain the widespread acceptance, includes support for server
certificates only. It provides the authentication of the server, confidentiality, and integrity. Here's
how it works:

 A user connects to the secure site using the HTTPS (HTTP plus SSL) protocol. (You can
detect sites using the HTTPS protocol because their URLs begin with https: instead of
http:.)

 The server signs its public key with its private key and sends it back to browser.

 The browser uses server's public key to verify that the same person who signed the key
actually owns it.

 The browser check to see whether a trusted certificate authority signed the key. If one
didn't, the browser asks the user if the key can be trusted and proceeds as directed.

 The client generates a symmetric ( DES) key for session, which is encrypted with the
server's public key and sent back to the server. This new key is used to encrypt all the
subsequent transactions. The symmetric key is used because of high computational cost of
public key cryptosystems

Connecting to database in Servlets

A servlet can create one or more Connectionobject in its init() method and reuse them in its
service(), doGet(), and doPost() methods.

To demonstrate, Example 9-4 shows the phone lookup servlet rewritten to create its Connection
objects in advance. It also uses HtmlSQLResult to display the results. Note that this servlet uses
the Sybase JDBC driver.

Servlets Database Connection Using Mysql database


// File: ShowBedrock.java

/* A servlet to display the contents of the MySQL Bedrock database */

36
import java.io.*;
import java.net.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowBedrock extends HttpServlet


{
public String getServletInfo()
{
return "Servlet connects to MySQL database and displays result of a SELECT";
}

// Use http GET

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException
{
String loginUser = "Dude1";
String loginPasswd = "SuperSecret";
String loginUrl = "jdbc:mysql://localhost:3306/bedrock";

response.setContentType("text/html"); // Response mime type

// Output stream to STDOUT


PrintWriter out = response.getWriter();

out.println("<html><head><title>Bedrock</title></head>");
out.println("<body><h1>Bedrock</h11>");

// Load the mm.MySQL driver


37
try
{
Class.forName("org.gjt.mm.mysql.Driver");
Connection dbcon = DriverManager.getConnection(loginUrl, loginUser, loginPasswd);
// Declare our statement
Statement statement = dbcon.createStatement();

String query = "select name, dept, ";


query += " jobtitle ";
query += "from employee ";

// Perform the query


ResultSet rs = statement.executeQuery(query);

out.println("<table border>");

// Iterate through each row of rs


while (rs.next())
{
String m_name = rs.getString("name");
String m_dept = rs.getString("dept");
String m_jobtitle = rs.getString("jobtitle");
out.println("<tr>" +
"<td>" + m_name + "</td>" +
"<td>" + m_dept + "</td>" +
"<td>" + m_jobtitle + "</td>" +
"</tr>");
}

out.println("</table>");

rs.close();
statement.close();
dbcon.close();
38
}
catch (SQLException ex) {
while (ex != null) {
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException ();
} // end while
} // end catch SQLException

catch(java.lang.Exception ex)
{
out.println("<html>" +
"<head><title>" +
"Bedrock: Error" +
"</title></head>\n<body>" +
"<p>SQL error in doGet: " +
ex.getMessage() + "</p></body></html>");
return;
}
out.close();
}
}

Filters in Servlet
 The Java Servlet specification version 2.3 introduce a new component type, called a filter.
 A filter dynamically intercepts the requests and responses to transform or use the
information contained in the requests or responses.
 Filters typically do not themselves create responses, but instead provide universal functions
that can be "attached" to any type of the servlet or JSP page.

Importance of Filters in Servlet

Filters are the important for a number of reasons.

 First, they provide ability to encapsulate recurring tasks in reusable units. Organized
developers are constantly on the lookout for ways to modularize their code. Modular code
39
is more manageable and documentable, is easier to debug, and if done well, can be reused
in the another setting.

 Second, filters can be used to transform response from a servlet or a JSP page. A common
task for web application is to format data sent back to the client. Increasingly the clients
require format (for example, WML) other than just HTML. To accommodate these clients,
there is usually a strong component of transformation or filtering in a fully featured the web
application. Many servlets and JSP containers have introduced proprietary filter
mechanisms, resulting in a gain for the developer that deploys on that container, but
reducing the reusability of such code. With the introduction of filters as part of Java Servlet
specification, developers now have the opportunity to write reusable transformation
components that are portable across containers.

Function of Filters

Filters can perform many different types of function:

 Authentication-Blocking requests based on user identity.


 Image conversion-Scaling maps, and so on.
 Logging and auditing-Tracking users of a web application.
 Data compression-Making downloads smaller.
 Localization-Targeting the request and response to a particular locale.
 XSL/T transformations of XML content-Targeting web application responses to more that
one type of client.

Filters Method

The most important method in Filter interface is the doFilter method, which is the heart of the
filter. This method usually performs some of the following actions:

 Examines the request headers


 Customizes the request object if it wishes to modify request headers or data or block the
request entirely

 Invokes the next entity in the filter chain.

 Customizes the response object if it wishes to modify response headers or data

40
If the current filter is the last filter in the chain that end with the target servlet, the next entity is the
resource at the end of the chain; otherwise, it is the next filter that was configured in the WAR. It
invokes the next entity by calling doFilter method on the chain object (passing in the request and
response it was called with, or the wrapped versions it may have created). Alternatively, it can
choose to block request by not making the call to invoke the next entity. In the latter case, the filter
is responsible for the filling out the response. Examines response headers after it has invoked the
next filter in the chain Throws an exception to indicate an error in processing In addition to
doFilter, you must implement init and destroy methods. The init method is called by the container
when the filter is instantiated. If you wish to pass initialization parameters to the filter you retrieve
them from the FilterConfig object passed to the init.

Example of using Filters in Servlet

The following example called HitCounter specifies the number of hits done in a paricular website

public final class HitCounterFilter implements Filter


{
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException
{

this.filterConfig = filterConfig;
}
public void destroy()
{
this.filterConfig = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (filterConfig == null)
return;
41
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
Counter counter = (Counter)filterConfig.
getServletContext().
getAttribute("hitCounter");
writer.println();
writer.println("===============");
writer.println("The number of hits is: " +
counter.incCounter());
writer.println("===============");

// Log the resulting string


writer.flush();
filterConfig.getServletContext().
log(sw.getBuffer().toString());

...
chain.doFilter(request, wrapper);
...
}
}

Servlets Summary
 A Servlet is a Java class that accept a request and generates a response.
 The Servlets that we are interested in are called HttpServlet.
 The HttpServlet accepts HTTP request and generates HTTP response.
 It is important to understand Servlet because they are the underlying implementation of
JSPs.
 The correlation between the JSP code and the Servlets code will be pointed throughout this
book to deepen your understanding of JSPs.

Quiz:

1. In which file do we define a servlet mapping ?


42
a) web.xml
b) servlet.mappings
c) servlet.xml
d) Simple.java
2. which of the following URLs will correctly request the Servlet ?
a) http://www.mywebapp.com/secureapp/Login?name="bob"
b) http://www.mywebapp.com/Login?name="bob"
c) http://www.mywebapp.com/secureapp/doLogin?name="bob"
d) http://www.mywebapp.com/secureapp/do/Login?name="bob"
3. Servlets and JavaServer Pages have become so popular that they are now supported directly or
with third-party plug-ins by most major Web servers and application servers.
a) True
b) False
c) Can't say
d) None of these
4. All servlets must implement the Servlet interface of package:
a) java.servlet
b) javax.servlet
c) .servlet
d) All are same

5. A get request gets information from a client. A post request posts data to a client.
a) True
b) False
c) Not always
d) None of these
6. The Web server that executes the servlet creates an _________ object and passes this to the
servlet's service method (which, in turn, passes it to doGet or doPost).
a) HttpServletResponce
b) HttpRequest
c) ServletRequest
d) HttpServletRequest
7. The client can access the servlet only if the servlet is installed on a ________ that can respond to
servlet requests.
43
a) client
b) server
c) Internet
d) in your network
8. Java Networking Java 1.1 natively supports which of the following protocols:
1. TCP
2. UDP
3. SMB
a) 1 and 2 only
b) 1 only
c) 2 and 3 only
d) 1 and 3 only
9. Which of the following describe ways that dynamic information can be made available to all
servlet requests sent to an application
a) Make the information available from a singleton
b) Store the information in the ServletContext
c) Store the information in an HttpSession
d) Store the information in a Properties file

10. Which statement is true about a non-static inner class ?


a) It must implement an interface
b) It is accessible from any other class
c) It must be final if it is declared in a method scope.
d) It can access private instance variables in the enclosing object
11. Which of the following can be used to store client side user state information while avoiding
any impact due to the users web browser configuration ?
a) Cookies
b) URL rewriting
c) HttpSessions
d) Hidden tags
12. Parameters are passed as _______ pairs in a get request.
a) value
b) name/value
44
c) Both can be used
d) None of these
13. The servlet initialization parameters are specified in the _______ deployment descriptor file as
part of a servlet element.
a) web.xml
b) web.Doc
c) web.txt
d) web.ini
14. Which of the following identifies the correct method a servlet developer should use to retrieve
form data from the client provided to the doPost() method ?
a) getParameter() against the HttpServletRequest object
b) getInputStream() against the HttpServletrequest object
c) getBytes() against the HttpServletrequest object
d) getQueryString() against the HttpServletrequest object
15. Which of the following is NOT true about servlets ?
a) They are instantiated every time a request is made.
b) They are a mechanism used by the class loader to download applets.
c) They can be used instead of CGI scripts.
d) They require a web browser that supports JDK 1.1

16. If you delete a field from a class and recompile the class, but then load an object that was
serialised before the new class was compiled what will happen?
a) The new object will contain all the data it used to but the new field is not accessible
b) The old class will be reloaded.
c) The new object will contain all the data it used to including the removed field
d) An exception will occur
17. Java Threads Which of the following can you do with the synchronized keyword:
1. Synchronise on an object
2. Synchronise on a static method
3. Synchronise around code that exists in a method of an instance of an object.
a) 1 and 2 only
b) 1 and 3 only
c) 1 only
45
d) 2 and 3 only
18. Using relative paths to reference resources in the same context root makes your Web
application more flexible.
a) False
b) True
c) Can't say
d) None of these
19. What is the servlet ?
a) Client side program
b) Srver side program
c) Both are true
d) None of these
20. What type of diagram does a Java Architect frequently produce ?
a) Attribute diagram
b) Property diagram
c) Constraint diagram
d) Package dependency diagram

Chapter II : JSP : Java Server Pages


It is a server side scripting language.
JSP are normal HTML with Java code pieces embedded in them.
A JSP compiler is used to generate a Servlet from the JSP page.
JavaServer Pages enables the development of dynamic web sites and it is based on Java language.
Introduction to Jsp

To allow server side development JSP was developed by Sun Microsystem. Typical
different clients connecting via the Internet to a Web server. e.g. a well popular Apache Web server
is execute on Unix platform.

C and Perl are languages which used on web servers to provide dynamic content. Most
languages including Visualbasic,Delphi,C and Java could be used to write application that
provided dynamic content using data from database requests. These were known as CGI server
side applications. Microsoft developed ASP to allow HTML developers to easily provide dynamic
46
content supported as standard by Microsoft free Web Server called Internet Information Server
(IIS). A comparison of ASP and JSP will be given in section below.

 JSP source code runs on the web server via JSP Servlet Engine.
 JSP files are HTML files with special Tags

containing Java source code that provide the dynamic content.


Why we used JSP?
JSP allow developer to quickly produce web sites and applications in an open and standard
way and it is easy to learn. JSP is Java based an object-oriented language and offers a robust
platform for web development
Reason to use JSP:
 Reusability of Components by using Javabeans and EJB.
 Multi platform
 Platform-Independent

So you are never depend on one vendor or platform.

HTML and graphics displayed on the web browser are the presentation layer and the Java code
(JSP) on the server is classed as the implementation.

Due to the separation of presentation and implementation,web designers work only on the
presentation and Java developers concentrate on implementing the application.

Comparison of JSP with ASP,ASP.NET and Servlet


Comparison with ASP

JSP and ASP provide fairly similar functionality.

 Both allow embedded code in an HTML page,session variables and database access and
manipulation.
 ASP is mostly found on Microsoft platform but JSP can operate on any platform that
conforms to the J2EE specification.

 JSP allow reusubility of component by using Javabeans and EJBs but ASP provides the use
of COM / ActiveX controls.

47
Comparison with ASP.NET
ASP.NET is based on the Microsoft .NET framework. By using .NET framework you developed
application with different programming language like Visual Basic,C# and JavaScript. JSP and
Java still has the advantage that it is supported on many different platforms and the Java
community has many years of experience in designing and developing Enterprise quality scalable
applications. ASP.NET is quite an improvement over the old ASP code.
Comparison with Servlets
A Servlet is a Java class that provides special server side service. It is tough to write HTML code
in Servlets. In Servlets you need to have lots of println statements to create HTML. JSP pages are
converted to Servlets so actually can do the same thing as old Java Servlets.
JSP architecture

JSP are built by SUN Microsystem servlet technology. JSP tag contain Java code and its file
extension is .jsp

The JSP engine parses the .jsp and create a Java servlet source file. Then it compile the source file
into a class file,this is done first time only therefore JSP is probably slower when first time it is
accessed.After this compiled servlet is executed and is therefore return faster.

48
Steps for JSP request:

 When the user goes to a JSP page web browser makes the request via internet.

 JSP request gets sent to the Web server.

 Web server recognises the .jsp file and passes the JSP file to the JSP Servlet Engine.

 If the JSP file has been called the first time,the JSP file is parsed,otherwise Servlet is
instantiated.

 The next step is to generate a special Servlet from the JSP file. All the HTML required is
converted to println statements.

 The Servlet source code is compiled into a class.

49
 The Servlet is instantiated,calling the init and service methods.

 HTML from the Servlet output is sent via the Internet.

 HTML results are displayed on the user's web browser

JSP environment

To Set JSP environment


For setting the JSP environment you should have a JDK(Java Development Kit).
Setting up the JSP
Download the latest JDK from the following URL:
http://java.sun.com/javase/downloads/index.jsp
Install through the setup.
One of the main problems of new Java developers have is setting the PATH and CLASSPATH.
For Windows 95/98/ME you edit the AUTOEXEC.BAT file with the new PATH and CLASSPATH
set the path and reboot your machine.
For Windows 2000/XP you edit the environment variables.
(Control Panel -> System -> Environment Variables).
Read the installation instructions properly as it may change with future releases. What you do is
add the location of java's bin folder to the Path variable and the classes you want in the
CLASSPATH variable

50
To Download the JSP environment

51
Download JSP environment from the web.
http://java.sun.com/products/jsp/index.jsp
The preferred option is to download the Tomcat. Tomcat is a free open source JSP and Servlet
engine,developed by Apache. Instructions to download Tomcat are given below.
http://tomcat.apache.org/
For Tomcat setup
To download Tomcat (current version 5.),go to the following URL:
http://tomcat.apache.org/download-55.cgi
Unzip the file into a directory and set an environment variable TOMCAT_HOME to your main
Tomcat directory:
For example,
set TOMCAT_HOME=c:\tomcat
To start the server change to the tomcat\bin directory and type:
startup
Open a web browser and in the address box type:
http://localhost:8080/ - this displays the example page.

Place any new JSP files in the "webapps" directory under your installed Tomcat directory.
For example,to run "first.jsp" file,copy the file into the "webapps/ROOT" directory and then open
a browser to the address:
http://localhost:8080/myfirst.jsp
This will show you the executed JSP file.
First JSP

JSP simply place Java inside the HTML pages

You can change HTML page extension to ".jsp" instead of ".html"extension.


How to create simple JSP page
<html>
<head>
<title>My first JSP page
</title>
</head>
<body>
<%@ page language="java" %>
52
<% out.println("Hello World"); %>
</body>
</html>

Type the above code into a text file. Name the file helloworld.jsp.
Place it in correct directory on your JSP web server and call it via your browser.
Notice that when page reload in the browser, it comes up with the current time.
The character sequence <%= and %> enclose Java expression, which are evaluated at run time.
Scriptlets
JSP allow you to write block of Java code inside the JSP You do this by placing your Java
code between <% and %> character (just like expressions, but without the = sign at the start of the
sequence.) This block of code is known as a "scriptlet". By itself, a scriptlet doesn't contribute any
HTML (as we will see down below.) A scriptlet contains Java code that is executed every time the
JSP is invoked.
Here is a modified version of our JSP, adding in a scriptlet.

<HTML>
<BODY>
<%
// This is a scriptlet. Notice that the "date"
// variable we declare here is available in the
// embedded expression later on.
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>

When above example execute, you will notice the output from the " System.out.println" on the
server log. This is a convenient way to do simple debugging.

By itself a scriptlet does not generate HTML. If a scriptlet want to generate HTML, it can use a
variable called "out". This variable does not need to be declared. It is already predefined for

53
scriptlet, along with some other variables. The following example shows how the scriptlet can
generate HTML output.
<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
// This scriptlet generates HTML output
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>
Here we generate HTML directly by printing to the "out" variable.
Request & Response Keyword
A "request" is a server-side processing which refers to the transaction between a browser
and the server. When someone enters a URL, the browser sends a "request" to the server for that
URL, and shows returned data. As a part of this "request", various data is available, including the
file the browser wants from the server, and if the request is coming from pressing a SUBMIT
button, the information the user has entered in the form fields.
The JSP "request" variable is used to obtain information from the request as sent by the
browser. For instance, you can find out the name of the client's host (if available, otherwise the IP
address will be returned.) Let us modify the code as shown:
<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
54
<%
out.println( date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost());
%>
</BODY>
</HTML>
A similar variable is "response". This can be used to affect the response being sent to the
browser. For instance, you can call response.sendRedirect( anotherUrl ); to send a
response to the browser that it should load a different URL. This response will actualy goes all the
way to the browser. The browser will then send a different request, to "anotherUrl".
Using JSP tags
 Declaration tag
 Expression tag
 Directive tag
 Scriptlet tag
 Action tag

Declaration tag

Declaration tag ( <%! %> )

 It allows the developer to declare variables or methods.


 Start with <%! and End with %>
 Code placed inside this tag must end in a semicolon ( ; ).

Declarations do not generate output so are used with JSP expressions or scriptlets.
For Example,

<%!
private int counter = 0 ;
private String get Account ( int accountNo) ;
%>

Expression tag
Expression tag ( <%= %>)
55
Expression tag allow the developer to embed any Java expression and is short for out.println().
A semicolon ( ; ) does not appear at the end of the code inside the tag.
e.g.to show the current date and time.
Date : <%= new java.util.Date() %>

Directive tag
Direcitve tag ( <%@ directive...>)

A JSP directive gives special information about the page to JSP Engine.
Three main types of directives are:
1) page - processing information for this page.
2) Include - files to be included.
3) Tag library - tag library to be used in this page.

Directives do not produce any visible output when the page is requested but change the way the
JSP Engine processes the page.
e.g.,you can make session data unavailable to a page by setting a page directive (session) to false.

1.Page Directive
This directive has 11 optional attributes that provide the JSP Engine with special processing
information. The 11 different attributes with a brief description is decribe in table given below:

<%@ page language =


Language Which language the file uses.
"java" %>

<%@ page extends =


Extends Superclass used by the JSP engine for the translated
"com.taglib... %>
Servlet.

Import all the classes in a java package into the current <%@ page import =
import
JSP page. This allows the JSP page to use other java "java.util.*" %>
classes.
session Default is set to true.
oes the page make use of sessions. By default all JSP
pages have session data available. There are

56
performance benefits to switching session to false.

<%@ page buffer =


buffer Controls the use of buffered output for a JSP page.
"none" %>
Default is 8kb
<%@ page autoFlush =
autoFlush Flush output buffer when full.
"true" %>

Can the generated Servlet deal with multiple requests?


isThreadSafe
If true a new thread is started so requests are handled
simultaneously.
<%@ page info =
Developer uses info attribute to
add "visualbuilder.com test
info
information/document for a page. Typically used to add page,copyright 2001. "
author,version,copyright and date info. %>

<%@ page errorPage =


errorPage Different page to deal with errors. Must be URL to error
"/error/error.jsp" %>
page.

This flag is set to true to make a JSP page a special


IsErrorPage
Error Page. This page has access to the implicit object
exception (see later).
Set the mime type and character set of
contentType
the JSP.

2. Include directive

It allows a JSP developer to include contents of a file inside another. Typically include files are
used for navigation,headers,tables and footers that are common to multiple pages.

Two examples of using include files:

This includes the html from privacy.html found in the include directory into the current jsp page.
<%@ include file = "include/privacy.html" %>
or to include a naviagation menu (jsp file) found in the current directory
<%@ include file = "navigation.jsp" %>
57
3. Tag Lib directive

A tag lib is a collection of custom tag that can be used by the page
<%@ taglib uri = "tag library URI" prefix = "tag Prefix" %>
Custom tag were introduced in JSP 1.1 and allow JSP developer to hide complex server side code
from web designers
Scriptlet tag
Scriptlet tag ( <% ... %> )
Between <% and %> tags,any valid Java code is called a Scriptlet. This code can access any
variable or bean declared. For example,to print a variable.

<%
String username = "visualbuilder" ;
out.println ( username ) ;
%>

Action tag
There are three main roles of action tag :
1) It enable the use of server side Javabeans
2) It transfer control between pages
3) Browser independent support for applets.

Javabeans
A Javabeans is a special type of class that has a number of methods. The JSP page can call
these method so can leave most of the code in these Javabeans. For example,if you wanted to make
a feedback form that automatically sent out an email. By having a JSP page with a form,when the
visitor presses the submit button this send the details to a Javabean that sends out the email. This
way there would be no code in the JSP page dealing with sending emails (JavaMail API) and your
Javabeans could be used in another page(promotingreuse).

To use a Javabeans in a JSP page use the following syntax:


<jsp : usebean id = " ...." scope = "application" class = "com..." />

58
The following is a list of Javabean scopes:
page - valid until page completes.
request - bean instance lasts for the client request
session - bean lasts for the client session.
application - bean instance created and lasts until application ends.
 Creating your second JSP page
 JSP Sessions

Creating your second JSP page

The different tags which we have learnt are using here. This example will declare two variables;
one string used to stored the name of a website and an integer called counter that displays the
number of times the page has been accessed. There is also a private method declared to increment
the counter. The website name and counter value are displayed.

<HTML>
<HEAD>
<!-- Example2 -->
<TITLE> JSP loop</TITLE>
</HEAD>
<BODY>
<font face=verdana color=darkblue>
JSP loop
<BR> <BR>
<%!
public String writeThis(int x)
{
String myText="";
for (int i = 1; i < x; i )
myText = myText "<font size=" i " color=darkred face=verdana>VisualBuilder JSP
Tutorial</font><br>" ;
return myText;
}
%>
This is a loop example from the <br>
59
<%= writeThis(8) %>
</font>
</BODY>
</HTML>

JSP Sessions

On any typical web site, a visitor might visit several pages and perform several interactions.
If you are programming the site, it is very helpful to be able to associate some data with each
visitor. For this purpose, "session"s can be used in JSP.
A session is an object associated with a visitor. Data can be put in the session and retrieved from it,
much like a Hashtable. A different set of data is kept for each visitor to the site.
Here is a set of pages that put a user's name in the session, and display it elsewhere. Try out
installing and using these.
First we have a form, let us call it GetName.html

<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

The target of the form is "SaveName.jsp", which saves the user's name in the session. Note
the variable "session". This is another variable that is normally made available in JSPs, just like out
and request variables. (In the @page directive, you can indicate that you do not need sessions, in
which case the "session" variable will not be made available.)

<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>

60
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
The SaveName.jsp saves the user's name in the session, and puts a link to another page,
NextPage.jsp.

NextPage.jsp shows how to retrieve the saved name.

<HTML>
<BODY>
Hello, <%= session.getAttribute( "theName" ) %>
</BODY>
</HTML>

If you bring up two different browsers (not different windows of the same browser), or run two
browsers from two different machines, you can put one name in one browser and another name in
another browser, and both names will be kept track of.

The session is kept around until a timeout period. Then it is assumed the user is no longer visiting
the site, and the session is discarded.

Implicit Objects

Implicit objects are a set of Java objects that the JSP Container makes available to developers in
each page.

These objects may be accessed as built-in variables via scripting elements and can also be accessed
programmatically by JavaBeans and Servlets.
Overview

Implicit objects will be automatically instantiated under specific variable names. Furthermore,each
object must adhere to a specific Java class or interface

61
definition.

We have already met one of these objects already - the out object in which we used the println()
method to add text to the output stream.

Object Class or Interface Description


page jsp.HttpJspPage Page's servlet instance
config ServletConfig Servlet configuration information
Provides access to all the namespaces associated with a
pageContext jsp.pageContext
JSP page and access to several page attributes
request http.HttpServletRequest Data included with the HTTP Request
response http.HttpServletResponse HTTP Response data, e.g. cookies
out jsp.JspWriter Output stream for page context
session http.HttpSession User specific session data
application
ServletContext Data shared by all application pages

The first three are rarely used. The application, session and request implicit objects have the
additional ability to hold arbitrary values. By setting and getting attribute values these objects are
able to share information between several JSP pages.

JSP Create Form

Beans and Form processing

Forms are a very common method of interactions in web sites. JSP makes easy forms processing.

To Create Form

Here we show how to create and process an html form. Code below you save as a file name
myform.jsp Go to myform.jsp in your browser and open it. It won't do anything yet.

<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>

62
</head>
<body>
<form action="myformconfirm.jsp" method="post">
Enter in a website name:<br>
<input type="text" name="website"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

Processing a Form
Code written here which process the html form your just created. Copy the code below and place
in a file named: myformconfirm.jsp Go to myform.jsp Fill in some details and submit the form You
should see the results of your submission
<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>
</head>
<body>
<font size=3>
Your info has been received:
<br><br>
<%
String sName = request.getParameter("website");
out.print(sName);
%>
</font>
</body>
</html>

Beans and Form Processing


The standard way of handling JSP forms is to define a "bean". This is not a full Java bean.
You just need to define a class that has a field corresponding to each field in the form. The class

63
fields must have "setters" that match the names of the form fields. For instance, let us modify
GetName.html to also collect email address and age.

The new version of GetName.html is


<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

To collect data, we define a Java class with fields "username", "email" and "age" and we
provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter" method is a
method that starts with "set" followed by the name of the field. The first character of the field
name is upper-cased. So if the field is "email", its "setter" method will be "setEmail". Getter
methods are defined similarly, with "get" instead of "set". Note that the setters & getters method
must be public.

package user;
public class UserData {
String username;
String email;
int age;
public void setUsername( String value )
{
username = value;
}
public void setEmail( String value )
{
email = value;
64
}
public void setAge( int value )
{
age = value;
}
public String getUsername() { return username; }
public String getEmail() { return email; }
public int getAge() { return age; }
}
The method names must be exactly as shown below. Once you have defined the class,
compile it and make sure it is available in the web-server's classpath. The server may also define
special folders where you can place bean classes, e.g. with Blazix you can place them in the
"classes" folder. If you have to change the classpath, the web-server would need to be stopped and
restarted if it is already running.
Note that we are using the package name user, therefore the file UserData.class must be placed in a
folder named user under the classpath entry.
Now let us change "SaveName.jsp" to use a bean to collect the data.
<jsp:useBean id="user" class="user.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>

Now we have to add the jsp:useBean tag and the jsp:setProperty tag! The useBean tag will
look for an instance of the "user.UserData" in the session. If the instance is already there, it will
update the old instance. Otherwise,it will create a new instance of user.UserData (the instance of
the user.UserData is called a bean), and put it in the session.

The setProperty tag will automatically collect the input data, match names against the bean method
names, and place the data in the bean!

Let us modify NextPage.jsp to retrieve the data from bean..

65
<jsp:useBean id="user" class="user.UserData" scope="session"/>
<HTML>
<BODY>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</BODY>
</HTML>

Notice that the same useBean tags is repeated. The bean is available as the variable named
"user" of class "user.UserData". The data entered by the user is all collected in the bean.

We do not actually need the "SaveName.jsp", the target of GetName.html could have been
NextPage.jsp, and the data would still be available the same way as long as we added a
jsp:setProperty tag. But in the next tutorial, we will actually use SaveName.jsp as an error handler
that automatically forwards the request to NextPage.jsp, or asks the user to correct the erroneous
data.

JSP Summary

In our tutorial with JSP we've gotten an idea of what JSP is good for, and how it's used.
We've seen that JSP gives us the power of Java on the Web server, which is an incomparable asset.
We have also taken a look at where JSP came from, and how it developed. We've seen that
as the Web has evolved, Java has been a part of the picture first with applets, then servlets, and
now JSP. Applets were nice, but limited; servlets are very powerful but complex. JSP gives us the
best of both worlds: They're both very powerful (they're converted to servlets before they're run)
and easy to write.
You've also installed the Tomcat server and gotten it running, and built the development
environment (Java, Tomcat, browser, and an editor) you'll be using in the coming days.
We've also developed and run our first JSP. Instead of having to write everything in Java,
we were able to simply insert the Java we wanted into an HTML page. That's the whole genius of
JSP—you use an HTML backbone and just add the Java you need. As we've also seen, JSP offers a
whole set of built-in objects, which means we can get away with even less Java because we don't
have to create those objects ourselves.

66
We also took a look at the JSP syntax in overview here—some of which might not have
made a great deal of sense yet. (But don't worry, that's why this is Day 1—it's all coming up in
depth in the next days.)
And that's it—we've started our in-depth guided tour of JSP, and built the foundation we'll
need in the coming days. Tomorrow, you'll see more details, such as how to work with data and
operators in JSP, and you'll start writing some real code.

Quiz:
1. Choose the statement that best describes the relationship between JSP and servlets:
a) Servlets are built on JSP semantics and all servlets are compiled to JSP pages for runtime
usage.
b) JSP and servlets are unrelated technologies.
c) Servlets and JSP are competing technologies for handling web requests. Servlets are being
superseded by JSP, which is preferred. The two technologies are not useful in combination.
d) JSPs are built on servlet semantics and all JSPs are compiled to servlets for runtime usage.

2. What is a benefit of using JavaBeans to separate business logic from presentation markup within
the JSP environment ?
a) It allows the JSP to access middleware.
b) It provides a dynamic markup environment, such that JavaBeans are integrated seamlessly
with the template presentation content, in order to create the dynamic display for the client.
c) It provides the developer with full access to the Java 2 Platform Enterprise Edition (J2EE),
which is unavailable from outside the JavaBean environment.
d) None of these
3. Why use RequestDispatcher to forward a request to another resource, instead of using a
sendRedirect ?
a) Redirects are no longer supported in the current servlet API.
b) Redirects are not a cross-platform portable mechanism.
c) The RequestDispatcher does not use the reflection API.
d) The RequestDispatcher does not require a round trip to the client, and thus is more efficient
and allows the server to maintain request state.
4. What alternatives exist to embedding Java code directly within the HTML markup of your JSP
page ?
a) Moving the code into your session manager.
67
b) Moving the code into scriptlets.
c) Moving the code into JavaBeans and servlets.
d) Moving the code into a transaction manager.
5. What type of scriptlet code is better-suited to being factored forward into a servlet ?
a) Code that deals with logic that is common across requests.
b) Code that deals with logic that is vendor specific.
c) Code that deals with logic that relates to database access.
d) Code that deals with logic that relates to client scope.
6. Choose the statement that best describes how to connect JSP pages and Enterprise JavaBeans
(EJBs):
a) Lookup the EJBs from within a JSP, but use the EJBs from within a basic JavaBean.
b) Lookup and use the EJBs from a separate business delegate. The JavaBeans that work with
JSP pages are clients to these business delegates and know nothing about EJB specifics.
c) Lookup the EJBs from within a servlet, delegating usage to specific JSP pages.
d) Lookup and use the EJBs from within a JSP page, but only as remote references.
7. Are custom tags available in JSP 1.0? If not, how else might you implement iteration from
within a JSP ?
a) Yes, but the only tags available relate to database access.
b) Yes, but custom tags will not help developers create tags for use in iterating over a
collection.
c) No. To iterate over a collection of values, one must use scriptlet code.
d) No, but there is a standard tag that may be used.
8. What is the initial contact point for handling a web request in a Page-Centric architecture ?
a) A JSP page.
b) A JavaBean.
c) A servlet.
d) A session manager.
9. What is the difference between doing an include or a forward with a RequestDispatcher ?
a) The two methods provide the same functionality, but with different levels of persistence.
b) The forward method is deprecated as of JSP 1.1 and the include method should be used in
order to substitute portions of a dynamic display at runtime.
c) The include method transfers control to a dynamic resource, while the forward method
allows for dynamic substitution of another JPS pages output, returning control to the
calling resource.
68
d) The forward method transfers control to the designated resource, while the include method
invokes the designated resource, substitutes its output dynamically in the display, and
returns control to the calling page.
10. Which of the following can the JSP include action include output from ?
a) Another JSP
b) Servlet
c) Plain text file
d) All of the above
11. The <jsp:include/< action can pass parameters to the page which it is including. How does this
second page obtain the
a) value of these parameters ?
b) Using the <jsp:readParam/> action
c) Using the <jsp:getParam/> action
d) Use the request.getParameter() method

12. What is wrong with the following code ?


<%
if(strPassword.equals("boss"))
{<jsp:forward page="Welcome.jsp" flush="true"/>}
else
{
}
%>
a) Unmatched bracket in for statement
b) Flush attribute must be false
c) Keyword 'file' should be used instead of 'page' in the <jsp:forward/> action
d) Actions cannot be used within scriptlet blocks

13. What is wrong with the following code ?


<jsp:include page="MainMenu.jsp" flush="true"/>
<%
Cookie c = new Cookie("UserName", "Alastair Gulland");
response.addCookie(c);
%>
69
a) Cookie class can not take parameters in it's constructor
b) The request object is used for creating cookies
c) Although no error will be reported the use of the <jsp:include/> action means that the
response object can't be used to create cookies.
d) The <jsp:include/> action must be placed inside the script block
14. When a JSP page is compiled, what is it turned into ?
a) Applet
b) Servlet
c) Application
d) Mailet
15. Which of the following is not a standard method called as part of the JSP life cycle ?
a) jspInit()
b) jspService()
c) _jspService()
d) jspDestroy()
16. If you want to override a JSP file's initialization method, within what type of tags must you
declare the method ?
a) <@ @>
b) <%@ %>
c) <% %>
d) <%! %>
17. Which of the following can not be used as the scope when using a JavaBean with JSP ?
a) application
b) response
c) request
d) session
18. What is the key difference between using a <jsp:forward> and
HttpServletResponse.sendRedirect()?
a) forward executes on the server while sendRedirect() executes on the client.
b) forward executes on the client while sendRedirect() executes on the server.
c) The two methods perform identically.
d) None of these
19. How can a servlet call a JSP error page?
a) This capability is not supported.
70
b) When the servlet throws the exception, it will automatically be caught by the calling JSP
page.
c) The servlet needs to forward the request to the specific error page URL. The exception is
passed along as an attribute named "javax.servlet.jsp.jspException".
d) The servlet needs to redirect the response to the specific error page, saving the exception
off in a cookie.
20. What is JSP ?
a) Java Server Pages
b) Java Special Pages
c) Java Static Pages
d) Java Showing Pages

71

Anda mungkin juga menyukai