Using and Writing Java Servlets
Creating dynamic web pages is necessary
if a web site wants to display the current state of data
accurately, for example showing temperatures around the world.
There are several ways to accomplish this, such as using Perl or
shell scripts. In this article, I discuss the viability of using
Java programs (servlets) with a web server. A servlet is a Java
application that performs a task that may generate a dynamic web
page or process input from a web page form.Advantages and Disadvantages of Using
ServletsThe first advantage is that only one instance of the JVM
(Java Virtual Machine) needs to be started. For each servlet, a new
thread is created and managed by the same JVM. In contrast, Perl
and shell CGI (common gateway interface) scripts require a new
process to be created each time the script is run. This may become
a problem if dynamic web pages are being created for many (possibly
thousands) of web pages per minute. The JVM itself is more
efficient because it only needs to keep one copy of the actual
servlet code to create the dynamic portions, such as variable data
and program context, for each instance of the servlet. Another plus
is that if you have Java expertise, it is not necessary to relearn
a new scripting language with a new set of APIs and quirks.Since the JVM has a rapport with the web server, it is
possible for servlets to communicate to the server directly. This,
of course, poses a security risk but does allow servlets to be
written that manipulate the web server on the fly.The user does not need to have a Java-capable browser because
there are still many small internet devices that do not have the
capacity to run complex Java APIs. Also, the Java servlet code is
portable across operating systems and machine architectures.None of the graphical user interface components of the Java
API can be used by a servlet, as its display is an HTML web page.
However, it is possible to use the imaging APIs to create graphs
and display them as a final rendered image. In addition, the
servlet has access not only to a vast amount of standard APIs for
accessing databases and other information but also to third party
APIs for Java.As Java progresses through various versions, APIs are
deprecated and eventually discarded, and sometimes even the
language itself is changed. This may not cause a problem as the
Java-generated pseudo code (a type of machine-independent machine
code) can still execute on a different version of the JVM. However,
at some point (several years down the line) you will be required to
recompile and port the servlet with the Java Development Kit (JDK)
of the day.Another disadvantage is that Java, unfortunately, is slow.
Although great strides have been made in performance improvements,
Java code will not be as fast as native executables but probably is
faster than several other popular scripting languages.Since the servlet manager (in this case Tomcat) is a Java
program and is separate from the web server, Apache, the
communication between the two is not instantaneous. This may
produce a performance hitch on heavily active web servers.Getting StartedThe biggest hiccup with servlets is the installation and
running of the various components that are required for servlet
support. Here is a list of some requirements:
- A Java installation. Although some Linux
distributions provide Java, the version may be limited in its API
set or may be an older version. - A web server that can support servlets. There are
several available. In this tutorial, I use Apache but recommend
Jetty as well. You need to have Apache installed and functioning
for servlet support. Most Linux distributions install Apache by
default and already have it running, so this may not be a
problem. - You need a mechanism by which the web server can
execute Java servlets. For example, a popular servlet support
extension to Apache is Tomcat. However, Linux distributions most
likely will not provide this mechanism, and you will need to
download it from the Web.
Gotchas for Apache and TomcatYou need to inform Tomcat of the location of the Java
distribution; if the installation process does not detect it at
install time, you will need to edit /etc/rc.d/init.d/tomcat. Be
particularly careful if you have more than one version of Java
installed (e.g., 1.1.18 and 1.2.2).Also, whenever Tomcat is restarted, the Apache server must be
restarted as well. This is to establish the communication path
between Apache and Tomcat. The Apache server can be restarted
without having to restart Tomcat.Making Sure It WorksPoint your web browser to
http://localhost.localdomain/examples/servlets/, and execute any
one of the examples to confirm that your installation and
environment is a success. Another way is to use
http://localhost:8080/.If you do experience problems, you will need to revisit the
setup documentation. Unfortunately, the documentation is not very
user-friendly for any of the servlet enablers I use. You also can
read the various FAQs and forums available on the Apache web site
and servlet enablers.The First ServletListing 1 is an example of creating a servlet. This example
will generate a web page that will display a simple message.Listing 1.
First ServletNote that a servlet extends the HttpServlet class. This is
located in the Tomcat installation directory, in this instance
/var/tomcat/lib/servlet.jar. When you want to generate HTML output,
it is necessary to obtain the output channel with
response.getWriter(). It also is necessary to set the CLASSPATH to
include the full names of the .jar files, e.g.,export
CLASSPATH=/var/tomcat/lib/servlet.jar:$CLASSPATHNext, compile with javac
FirstServlet.java. Ensure that you are using the same JDK
that Tomcat has been set up to use (as described
previously).To make things simpler for the this exercise, place the
generated .class files into /var/tomcat/webapps/examples/servlets
(the actual configuration of Apache and Tomcat are beyond the scope
of this article). To execute the servlet, open the web page at
http://localhost.localdomain/examples/servlet/FirstServlet or
http://localhost:8080/servlet/FirstServlet. And
viola, the output seen below has been created
dynamically:Hello Fellow ServletsCreating a Table of Useful InformationListing 2 not only demonstrates how to display useful
information, but also shows the security concerns involved.
Servlets must be written so that no input from a remote browser can
give a cracker access to certain resources. Even something simple,
like causing an error in the servlet, may cause the JVM to perform
differently.Listing 2.
TableServletThe example generates the HTML code for a table, which a
selective query populates by the output provided from a system API
to retrieve certain configuration variable settings (see Listing
3). This, for instance, can be used as a template to a database
query using JDBC (Java Database Connectivity).Listing 3.
TableServlet OutputProcessing Form InputListing 4 demonstrates how a servlet can not only generate
dynamic web pages, but also process incoming data via an HTML form.
To process input from a form, it is necessary for the servlet to
override two functions: doGet and doPost. The doGet function always
needs to be defined and forms the default behavior of the servlet
and the processing of HTML form data sent via the GET method. The
doPost function is used only when HTML form data is sent using the
POST method, which is a more robust way than the GET method. In
this example, doGet reports an error because it will be invoked
only if the HTML form data was not sent with the POST method. In
the doPost function, the request.getParameter calls are used to
retrieve the corresponding parameter's value. Those of you who have
used other CGI scripts may notice that this is a very simple and
straightforward way to retrieve these values, which usually can end
up being an onerous task.Listing 4.
InputServletListing 5 shows the HTML input form, which a servlet could
also have generated. Figure 1 shows a snapshot of this form.Listing 5.
InputServlet HTML Input FormFigure 1. InputServlet HTML
Input Form SnapshotThe output reorganizes the entered data and displays it as an
HTML page:Hello, your name is Polly, Molly
PollyAgain, this data could have been passed to a file or
database.More and MoreOf course, these examples show servlets completing simple
tasks. Servlets can be expanded easily to handle cookies and keep a
session for a person's range of activities, such as logging in to
access certain data and then logging out.ConclusionThe configuration of the web server to support servlets can
be troublesome. However, servlets, with the power of the Java API
set, can provide complex dynamic webs pages and form
processing.ResourcesPetr Sorfa is a member of
Santa Cruz Operation's Development Systems Group, where he is the
maintainer of the cscope and Sar3D open-source projects.
email: petr@sco.com










This week 5 lucky Members will receive a copy of The Official Ubuntu Server Book by Benjamin Mako Hill and Linux Journal's very own Kyle Rankin. No entry necessary. Check back here early next week to find out who the lucky Online Members are.




Comments
code to display charts
i want to display more than one cahrts in a web page by using java by passing x-axis nad y-axis. and the data should fetch from oracle database. the query should execute in the backend.
Can u pls sort this out
hi.thanks for the wonderful stuff.
i have a problem, however.
I developed a login form in html,got it validated for user authentication through java servlets,and if user is valid the servlet is redirected to another html page, but now i wish to edit certain tags of the html page before redirection, kindly find some time to answer this soon.
Posting from Http DoPost without html form
Hi,
How can I call DoPost directly from the code, without html post method?
Thanks,
Re: Using and Writing Java Servlets
Good review. Right on target on the configuration being troublesome. The beating of old drums such as 'recompiling for new API's' or 'Java is slow' is unfortunately pure bantor. Everybody in every language recompiles code from time to time. And saying 'java is slow' is akin to the windoz jokers preaching that 'linux has no desktop interface'. How very yesterday....
running servlet
Hi,
I tried your example of form response servlet. Can you tell me where should I put the html form file and the class file of the sevlet? so that I can try it on Abyss Server/Tomcat/Servletrunner
Thanks,
Alankar
Re: Using and Writing Java Servlets
I like the tutorial, it will help me learn. I wish some of the value judgements could have been left out. I am, however, sick of Java people bashing "scripting" langs that they clearly have no knowledge of.
Eric
Re: Using and Writing Java Servlets
I really like this Tutorial too! I just start using Servlet yesterday and I have already create a WebApp information Table from what I have learned from this session. Thank you!
==Sandy
Re: Using and Writing Java Servlets
No credit is given to mod_perl, which only loads one instance of the Perl interpreter. Within mod_perl, pages are compiled once and run many times during the life of the server process. Many major web sites use the power of mod_perl to leverage the speed of Apache and the power and flexibility of Perl to generate rich, dynamic, and lightning-fast Web sites.
Re: Using and Writing Java Servlets
The article is not about mod_perl. However I do agree the article is a bit misleading as nobody in their right mind uses perl/php via CGI with Apache.
I like this article but can u
I like this article but can u plz tell me the full way to run Servlet on tomcat.And how to modified or create web.xml for the servlet.
Post new comment