Unit 6 - Java Server Programming
Unit 6 - Java Server Programming
Unit 6 - Java Server Programming
Chapter 6
Java Server Programming
Servlets
Servlets are Java technology's server side programming. They are programs that run on a
Web server for building dynamic web pages. Servlets are small programs that execute on
the server side of a web connection. Just as applets dynamically extend the functionality
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
exactly 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 are a great way to get this dynamic information
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
request 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
parameters 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 servlet 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
destroy() 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.
Why Servlets?
The HTTP protocol provides a framework for communicating with a server, where all the
real work is done. The server-side code may do load-balancing to move incoming
1
Java Server Programming Unit 6
requests 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.
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.
Servlets shares a common database connection across multiple requests. Servlets can
be run on different servers and platforms without modifications. This is important for
building enterprise-wide distributed applications.
Servlets are much more secure. 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 For Servlet</h1>");
pw.println("</body>");
pw.println("</html>");
}
}
2
Java Server Programming Unit 6
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
below:
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
environment.
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
commonly 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
session value, or that a session attribute changed.
3
Java Server Programming Unit 6
<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
1. Web browser requests for a JSP
2. The JSP request gets sent to the Web server.
3. The Web server recognizes that the file required is special (.jsp), therefore passes
this JSP file to the JSP Servlet Engine.
4. If the JSP file has been called the first time, the JSP file is parsed, otherwise go to
step 7.
5. The next step is to generate a special Servlet from the JSP file. The entire HTML
is converted to println statements.
6. The Servlet source code is compiled into a class.
7. The Servlet is instantiated, calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
9. HTML results are displayed on the user's web browser.
4
Java Server Programming Unit 6
5
Java Server Programming Unit 6
For example:
<!-- comment text <%= expression %> more comment text ->
Directive tag ( <%@ directive ... %>) – A JSP directive gives special information about
the page to the JSP Engine. Directives do not produce any visible output when the page is
requested but change the way the JSP Engine processes the page. For example, you can
make session data unavailable to a page by setting a page directive (session) to false.
There are three main types of directives:
i. Page Directive - processing information for this page. This directive has 11
optional attributes that provide the JSP Engine with special processing
information. The following table lists the 11 different attributes with a brief
description:
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" %>
6
Java Server Programming Unit 6
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.
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
dealing with sending emails (JavaMail API) and your Javabean could be used in another
7
Java Server Programming Unit 6
page.
Creating a Form
<html>
<head>
<title>JSP Demo</title>
</head>
<body>
<form action="myjsp.jsp" method="post">
Enter your name:<br>
<input type="text" name="yname"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Processing a Form
<html>
<head>
<title>JSP Demo</title>
</head>
<body>
<%
8
Java Server Programming Unit 6
String n = request.getParameter("yname");
out.print(n);
%>
</body>
</html>