Chapter 6-Java Server Programming
Chapter 6-Java Server Programming
When a CGI program is called, the information that is made available to it can be roughly
broken into three groups:
Information about the client, server, and user
Data supplied by the user
Additional pathname information
CGI programs are requested like any other regular documents. The difference is that in-
stead of returning a static document, the server executes a program and returns its output.
As far as the browser is concerned, however, it expects to get the same kind of response
that it gets when it requests any document, and it's up to the CGI program to produce out-
put that the browser is comfortable with.
The most basic output for a CGI program is a simple document in either plain text or
HTML, which the browser displays as it would any document on the Web. However,
there are other things you can do, such as:
Return graphics and other binary data
Tell the browser whether to cache the virtual document
1
Compiled BY Ramesh Bhatta
Servlets
Servlets are Java technology's answer to CGI programming. They are programs that run
on a Web server for building dynamic web pages. Servlets are small programs that exe -
cute on the server side of a web connection. Just as applets dynamically extend the func-
tionality of a web browser, servlets dynamically extend the functionality of a web server.
An ordinary page of HTML is static. Each time the server sends it out, it sends ex-
actly the same data. The only way it changes is if someone updates the HTML file with
an editor. But many kinds of information change dynamically: stock prices, the weather,
seats available on a flight, amount of inventory on hand, account balance, contents of an
online shopping cart, and so on. Servlets JSP are a great way to get this dynamic informa-
tion into a web page. Servlets are the most popular way for a browser to get a dynamic
web page from a program on the server.
The Life Cycle of Servlet
Three methods are the central to the life cycle of a servlet. These are init(), service(), and
destroy(). They are implemented by every servelet and are invoked at specific times by
the server.
First, a user enters a URL to a web browser. The browser then generates an HTTP re-
quest for this URL. This request is then sent to the appropriate server.
Second, this HTTP request is received by a web server. The server maps this request
to a particular servlet. The servlet is dynamically retrieved and loaded into the address
space of the server.
Third, the server invokes the init() method of the servlet. This method is invoked only
when the servlet is first loaded into memory. It is possible to pass initialization parame -
ters to the servlet so it may configure itself.
Forth, the server invokes the service() method of the servlet. This method is called to
process the HTTP request. You will see that it is possible for the servlet to read data that
has been provided in the HTTP request. It may also formulate an HTTP response for the
client. The server remains in the server’s address space and is available to process any
other HTTP requests received from clients. The service() method is called for each HTTP
request.
Finally, the server may decide to unload the servlet from its memory. The algorithms
by which this determination is made are specific to each server. The server calls the de-
stroy() method to relinquish any resources such as file handles that are allocated for the
servlet. Important data may be saved to a persistent store. The memory allocated for the
servlet and its objects can then be garbage collected.
2
Compiled BY Ramesh Bhatta
quests to the system best equipped to handle them. The server code can access/update
your database and process any data using the most up-to-date information.
CGI was the first attempt to get dynamic content into web pages. CGI got the job
done, but it had big problems with security and performance.
Since most servlets run in the process space of server and loaded only once, they are
able to respond much more quickly and efficiently to client requests. In contrast, CGI
must create new process to service each new request. The overhead involved in creating a
new process incurs a significant performance penalty.
Servlets shares a common database connection across multiple requests but CGI re-
quires new database connection for each request. Creating a database connection is
costly.
Portability is another strong advantage of for servlets. Unlike many CGI applications
servlets can be run on different servers and platforms without modifications. This is im-
portant for building enterprise-wide distributed applications.
Servlets are much more secure than CGI. Untrusted servlets run inside a sandbox in
the server. Sandbox is a protocol memory space wherein a program cannot access outside
resources such as file or network services.
Servlets make it easier to separate the business logic used to generate results from the
HTML that displays those results. Separation of logic from presentation has benefits. It is
an enabler for the use of component software such as Java Beans.
A Simple Servlet
Servlets are a higher-level alternative to reading/writing sockets. Servlets can be used to
service any request that is made via a socket (such as FTP), not just web page requests
via HTTP. A servlet that talks something other than HTTP is called a "generic servlet"
and it will extend the class javax.servlet.GenericServlet. The vast majority
of servlets are used to serve HTTP requests. These are known as "HTTP servlets," and
they extend the class javax.servlet.http.HttpServlet. For example,
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Test extends HttpServlet {
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Servlet Test</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("<h1>This is Fro Servlet</h1>");
pw.println("</body>");
pw.println("</html>");
3
Compiled BY Ramesh Bhatta
}
}
The Servlet API
Tow packages contain the classes and interfaces that are required to build servlets. These
are javax.servlet and javax.servlet.http. They constitute the Servlet API. These pack-
ages are not part of the Java core API.
The javax.servlet package contains a number of interfaces and classes that establish
the framework in which servlets operate. Its interfaces and classes are summarized be-
low:
Interface Description
Servlet Declares life cycle methods for a servlet
ServletConfig Allows servlets to get initialization parameters
ServerContext Enables servlets to log events and access information about their envi-
ronment.
ServletRequest Used to read data from a client request.
ServerResponse Used to write data to a client response.
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a client.
ServerOutputStream Provides an output stream for writing responses to a client.
ServerException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable.
The javax.servlet.http package contains a number of interfaces and classes that are com-
monly used by servlet developers. Its functionality makes it easy to build servlets that
work with HTTP requests and responses. The following tables summarize core interfaces
and classes that are provided:
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP request.
HttpServletResponse Enables servlets to write data on an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound from a
session.
Class Description
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods that handle HTTP requests and responses.
HttpSessionEvent Encapsulates a session-changed event.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a ses-
sion value, or that a session attribute changed.
4
Compiled BY Ramesh Bhatta
Java server pages (JSP) is a technology based on the java language and enables the devel-
opment of dynamic web sites. JSP was developed by Sun Microsystems to allow server
side development. JSP simply puts Java inside HTML pages. JSP files are HTML files
with special tags containing java source code that provide the dynamic content.
JavaServer Pages (JSPs) are, in the most basic sense, Web pages with embedded Java
code. The embedded Java code is executed on the server before the page is returned to
the browser. Following program shows a basic JSP.
<html>
<body>
<%
out.println("<h1>Hello World!</h1>");
%>
</body>
</html>
As you can see, the page is composed of standard HTML with a dash of Java contained
between the <% and %> character sequences. The <% and %> along with the code inside is
called a scriptlet.
Steps Required for a JSP Request
The user goes to a web site made using JSP. The user goes to a JSP page (ending
with .jsp). The web browser makes the request via the Internet.
1. The JSP request gets sent to the Web server.
2. The Web server recognizes that the file required is special (.jsp), therefore passes
this JSP file to the JSP Servlet Engine.
3. If the JSP file has been called the first time, the JSP file is parsed, otherwise go to
step 7.
4. The next step is to generate a special Servlet from the JSP file. The entire HTML
is converted to println statements.
5. The Servlet source code is compiled into a class.
6. The Servlet is instantiated, calling the init and service methods.
7. HTML from the Servlet output is sent via the Internet.
8. HTML results are displayed on the user's web browser.
5
Compiled BY Ramesh Bhatta
6
Compiled BY Ramesh Bhatta
language Which language the file uses. <%@ page language = "java" %>
extends Superclass used by the JSP engine <%@ page extends = "com.taglib...
for the translated Servlet. %>
import Import all the classes in a java <%@ page import = "java.util.*"
package into the current JSP page. %>
This allows the JSP page to use
other java classes.
session Does the page make use of <%@ page session = "false" %>
sessions? By default all JSP pages
have session data available. There
are performance benefits to
switching session to false. Default
is true.
buffer Controls the use of buffered <%@ page buffer = "none" %>
output for a JSP page. Default is
8kb
autoFlush Flush output buffer when full. <%@ page autoFlush = "true" %>
7
Compiled BY Ramesh Bhatta
date info.
ii. Include Directive – Allows a JSP developer to include contents of a file inside
another. Typically include files are used for navigation, tables, headers 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" %>
iii. Tag Library Directive – A tag lib is a collection of custom tags that can be used
by the page.
<%@ taglib uri = "tag library URI" prefix = "tag Prefix" %>
Custom tags were introduced in JSP 1.1 and allow JSP developers to hide
complex server side code from web designers.
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 tags:
1) Enable the use of server side Javabeans. For example, <jsp:usebean attributes />
2) Transfer control between pages.
3) Browser independent support for applets.
JavaBeans
A JavaBean is a special type of class that has a number of methods. The JSP page can
call these methods so can leave most of the code in these JavaBeans. For example, if you
want 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 sends the details to a
Javabean that sends out the email. This way there would be no code in the JSP page
8
Compiled BY Ramesh Bhatta
dealing with sending emails (JavaMail API) and your Javabean could be used in another
page.
Creating a Form
Here we show how to create and process an html form.
Copy the code below and place in a file named: myform.jsp
Go to myform.jsp in your browser
You will see the form you just created.
It won't do anything yet.
<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>
</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>
9
Compiled BY Ramesh Bhatta
Processing a Form
Here we show how to 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>
10
Compiled BY Ramesh Bhatta
<option value="jdbc">jdbc</option>
</select>
<br>
<br>
Description:
<textarea rows="4" cols='42' name="desc"></textarea>
<br>
<br>
Search engines:
<input type="checkbox" name="yahoo" value="T">Yahoo
<input type="checkbox" name="google" value="T" CHECKED>Google
<input type="checkbox" name="altavista" value="T">Altavista
<br>
<br>
<input type="submit" name="submit" value="Go">
</form>
</body>
</html>
</head>
<body>
<font size=3>
Thank you for your submission,it has been successfully received:
<br><br>
<%
String sName = request.getParameter("website");
String sUrl = request.getParameter("url");
String sCategory = request.getParameter("category");
String sDesc = request.getParameter("desc");
String sGoogle = request.getParameter("google");
String sYahoo = request.getParameter("yahoo");
String sAltavista = request.getParameter("altavista");
%>
Name:<%=sName%><br>
Url:<%=sUrl%><br>
Desc:<%=sDesc%><br>
Category:<%=sCategory%><br>
Desc:<%=sDesc%><br>
Google:<%=sGoogle%><br>
Yahoo:<%=sYahoo%><br>
Altavista:<%=sAltavista%><br>
11
Compiled BY Ramesh Bhatta
</font>
</body>
</html>
12