    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Servlets</title>
        <link>https://members.accu.org/index.php/articles/1037</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 12, #4 - Jul 2000</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c125/">124</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-125/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+125/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Servlets</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 July 2000 13:15:38 +01:00 or Mon, 03 July 2000 13:15:38 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p>What is a servlet and why use one?</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a>What is a
servlet and why use one?</h2>
</div>
<p>A servlet is a piece of Java code that is designed to expand the
functionality of a web server in some specific manner - for example
interrogating a database and formatting the results into a
displayable form.</p>
<p>Servlets are intended to generate dynamic web content. Because
they are written in Java, and Java itself is intended to be WORA
(Write Once, Run Anywhere), you can develop (and, perhaps more
importantly, debug) a servlet on Windows NT. The servlet can then
be deployed on to a Unix server with a high degree of confidence
that it will function correctly. Also, as no code is ever executed
on the client, you <span class="bold"><b>know</b></span> what
version of Java is running and can develop for that one and only
that one.</p>
<p>Once a servlet has been requested it can stay in memory (at the
garbage collector's discretion), which will allow any repeat call
to use a small, lightweight, method call so unlike CGI it is not
necessary to spawn a new process or invoke an interpreter. Since
servlets are multi-threaded, separate threads can handle multiple
concurrent requests, which gives high scalability.</p>
<p>Since this is Java you have access to the power of the Java API
- multi-threading, networking, database access,
internationalisation and much more - all of which is available for
you to use without having to write (or debug) a line of code. If
something does not come as standard with the JDK (Java Developer
Kit), there are lots of third-party libraries available and these
are just as usable with servlets as in 'normal' Java programs.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e34" id="d0e34"></a>The basics</h2>
</div>
<p>Servlets use classes and interfaces from two packages:
<tt class="literal">javax.servlet</tt> and <tt class=
"literal">javax.servlet.http</tt>. Every servlet must implement the
<tt class="classname">javax.servlet.Servlet</tt> interface, however
most developers choose to extend <tt class=
"classname">javax.servlet.http.HttpServlet</tt> as it has easier
access to the information supplied by the http protocol.</p>
<p>Unlike a Java application there is no <tt class=
"methodname">main()</tt> method - like a service, your code does
not do anything until it is invoked, in this case by the web
server. When a web server wants something doing it will call the
servlets <tt class="methodname">service()</tt> method. The
<tt class="methodname">service()</tt> method accepts two
parameters; one of type <tt class=
"classname">HttpServletRequest</tt> and one of type <tt class=
"classname">HttpServletResponse</tt>.</p>
<p>A servlet typically does not override the <tt class=
"methodname">service()</tt> method, instead it overrides one, or
more, of the 'do' methods; <tt class="methodname">doGet</tt>,
<tt class="methodname">doPost</tt>, <tt class=
"methodname">doPut</tt>, <tt class="methodname">doDelete</tt>. The
<tt class="methodname">HttpServlet.service()</tt> will call the
appropriate 'do' method, forwarding the request and response
objects.</p>
<p>The http request object, extended from <tt class=
"classname">ServletRequest</tt>, encapsulates information about the
client request; parameters and attributes along with support for
cookies, session tracking and access to the HTTP header
information. The http response object, extended from <tt class=
"classname">ServletResponse</tt>, is used to send data back to the
client and manipulate HTTP protocol-specific data including
response headers and status codes, cookies and session tracking.
Binary information can be streamed or written and characters can be
written out. This allows servlets to be written which can
manipulate images, access databases, and do anything you wish.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e96" id="d0e96"></a>An
example?</h2>
</div>
<p>The servlet that follows enumerates all the input data it
receives&hellip; more useful than you might think&hellip;</p>
<pre class="programlisting">
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Enumeration;

  public class ShowData extends HttpServlet {
  protected void doGet(HttpServletRequest req
              , HttpServletResponse resp)
  throws ServletException, java.io.IOException {
    resp.setContentType(&quot;text/html&quot;);
    printWriter out = res.getWriter();
    out.println(&quot;&lt;html&gt;&lt;body&gt;&quot;);
    out.println(&quot;A get operation&lt;br&gt;&quot;);
    out.println(enumParameter(req).toString());
    out.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;);
  }
  protected void doPost(HttpServletRequest req
            , HttpServletResponse resp)
  throws ServletException, Java.io.IOException {
    resp.setContentType(&quot;text/html&quot;);
    printWriter out = res.getWriter();
    out.println(&quot;&lt;html&gt;&lt;body&gt;&quot;);
    out.println(&quot;A post operation&lt;br&gt;&quot;);
    out.println(enumParameter(req).toString());
    out.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;);
  }
  private StringBuffer enumParameters( 
                  HttpServletRequest req)
  throws ServletException, java.io.IOException {
    StringBuffer buffer = new StringBuffer(
     &quot;Parameters supplied to the ShowData 
                    servlet:&lt;BR&gt;&lt;BR&gt;&quot;);
    Enumeration values = req.getParameterNames();
    while(values.hasMoreElements()) {
      String name=(String)values.nextElement();
      String value[] = 
            req.getParameterValues(name);
      for(int i = 0; i &lt; value.length; ++i){
        buffer.append(name).append(&quot; [&quot;).
         append(i).append(&quot;] : &quot;). 
          append(value[i]).append(&quot;&lt;br&gt;&quot;);
      }
    }
    return buffer;
  }
}
</pre>
<p>The example above splits easily into three sections: <tt class=
"methodname">doGet</tt>, <tt class="methodname">doPost</tt> and
<tt class="methodname">enumParameters</tt>. <tt class=
"methodname">enumParameters</tt> is, obviously, the work horse with
the others just saying how the parameters were passed to the
servlet. Easy isn't it?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e117" id="d0e117"></a>Some
warnings&hellip;</h2>
</div>
<p>Writing servlets is not without its heartaches. The main problem
is debugging. If like me, you write perfect code every time, first
time, you have nothing to worry about. I wish. So, you write the
code, it compiles, you write the surrounding html, fire off
navigator and&hellip; nothing. What do you do? Here are some
hints&hellip;</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Check the logs for problems. The web server writes here, so does
the Servlet Engine.</p>
</li>
<li>
<p>Output extra information - a return to 'proper' debugging as the
old timers will tell you - &quot;I remember when&hellip;&quot;</p>
</li>
<li>
<p>Examine your inputs - the <tt class=
"classname">HttpServletRequest</tt> object; sometimes we do not get
what we want. Ensure what you do get is what you expect.</p>
</li>
<li>
<p>Check the <tt class="literal">classpath</tt> of the servlet:
<tt class="literal">System.getProperty( &quot;Java.class.path&quot;)</tt>,
remember it is probably running as either a demon or service with
all the limitations imposed. Programs using JNI can be especially
difficult to work out <span class="emphasis"><em>why</em></span> it
does not work.</p>
</li>
<li>
<p>Avoid unnecessary creation of objects - this wastes both time
and memory and may block the JVM while it is doing so (JVM
dependent).</p>
</li>
<li>
<p>Do <span class="bold"><b>not</b></span> concatenate - append.
<tt class="classname">StringBuffer</tt>s are always an easy method
of optimising string handling in Java and it is much more important
with servlets.</p>
</li>
<li>
<p>Limit synchronization. Synchronise whenever necessary, but only
when necessary. If this is a problem, create a pool of objects and
serve the client from them, or better yet, buy a third party
pooling class (saves you debugging yet another implementation).</p>
</li>
<li>
<p>Run JWS (Java Web Server) under a debugger and use this to load
your servlet.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e165" id="d0e165"></a>The
future?</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e168" id="d0e168"></a>JSP</h3>
</div>
<p>JavaServer Pages are Sun's equivalent to Microsoft's
ActiveServer Pages. Just like ASP, JSP is a method of embedding
Java code within html pages. What has this to do with servlets?
Everything. Unlike ASP, JSP is not interpreted. Upon the first
request for a page containing JSP the Servlet Engine takes the
html, creates a Java file containing all the code, serialises out
the text to a file, compiles the Java into a servlet and invokes
it. The servlet serialises in the text from the file and proceeds
to write out to the response object the html while executing the
Java code. The next request from a client will start the process by
invoking the servlet. Simplicity.</p>
<p>This gives several advantages and as usual, some
disadvantages:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>if the html file alters the servlet is regenerated.</p>
</li>
<li>
<p>easy for experienced developers to write quick and dirty
solutions.</p>
</li>
<li>
<p>difficult for non-technical people to understand let alone
maintain or extend.</p>
</li>
<li>
<p>unless very careful the data and display, content and
presentation information are intermixed. This is the same as the
argument for three tier programs. Splitting off the code to
retrieve the data from the business objects and separating the GUI
gives interfaces that can be independently tested.</p>
</li>
</ul>
</div>
<p>The last disadvantage is, in my opinion, the big problem with
both JSP and ASP. If JSP is written correctly, the embedded Java
should only manipulate business objects. If this is not the case
then the page/content becomes extremely difficult to maintain and,
after all, do you want to continue to maintain projects forever?
Every time 'web designers' change the colour scheme, are you
willing to make sure they do not break something? I did not think
so.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e190" id="d0e190"></a>XML &amp;
XSP</h3>
</div>
<p>XML (eXtended Markup Language) - this is the technology of the
moment, along with XSL (eXtended Stylesheet Language) and XSLT
(eXtended Stylesheet Language Transformation) the data can be
completely separated from the layout. Wow! The data team can be
taught to write XML (especially if they are forced to use a
validating parser) and the design team can be shown how to alter
the XSL(T) file to display the page as they want. Nothing for the
developer to do - <span class="bold"><b>I like this</b></span>. Oh
dear, here comes the boss. He wants some dynamic content. He wants
the sales database linked to the web. Problem - XML is static.</p>
<p>The solution (in case you did not guess) is being developed by
the XML Apache group [<a href="#cocoon">cocoon</a>]. XSP is for XML
what JSP is for html. It allows embedding Java within XML. It works
along similar principles to JSP; it takes the XML, creates a Java
file, compiles it to a servlet and invokes it. One of the reasons
this approach is so much better than JSP is that the servlet only
produces data. XSL still controls the styling of the data, so once
the XML is written the design team can change how it is displayed
without bothering the developer.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e203" id="d0e203"></a>Finally</h2>
</div>
<p>Servlets are a very good example of how to write web server
extensions and you can see that several more new technologies are
being built on and around their functionality. They are simple to
write. I recommend that you write a couple before moving onto JSP
and XML, as your ability to program in these environments will be
greatly enhanced by opening the Java files created and
understanding what has been generated from your original files.
Both JSP and XSP are evolving extremely quickly. XSP is especially
useful by completely separating content from presentation; it
really is amazing what it can do. XML also has the advantage that
it can be transformed into a multitude of other mark-up forms: WML
(WAP (Wireless Application Protocol) Markup Language), SVG
(Scalable Vector Graphics) and even PDF (Portable Document Format)
(using FOP3).</p>
<p>Wow, my first article and written in under 3 hours! Please do
not be too critical but do feel free to contact me. I have to admit
however that I could not have written this thing so fast without
the Java Servlet bible [<a href="#Hunter-">Hunter-</a>]. If you are
planning to write any servlets this book will be your constant
companion.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e213" id="d0e213"></a>References:</h2>
</div>
<div class="bibliomixed"><a name="jakarta" id="jakarta"></a>
<p class="bibliomixed">[jakarta] <span class="bibliomisc"><a href=
"http://jakarta.apache.org" target=
"_top">http://jakarta.apache.org</a> Servlet Engine with support
for JSP</span></p>
</div>
<div class="bibliomixed"><a name="apache" id="apache"></a>
<p class="bibliomixed">[apache] <span class="bibliomisc"><a href=
"http://Java.apache.org" target="_top">http://Java.apache.org
Servlet Engine</a></span></p>
</div>
<div class="bibliomixed"><a name="cocoon" id="cocoon"></a>
<p class="bibliomixed">[cocoon] <span class="bibliomisc"><a href=
"http://xml.apache.org" target="_top">http://xml.apache.org</a>
Cocoon XML publishing engine</span></p>
</div>
<div class="bibliomixed"><a name="Hunter-" id="Hunter-"></a>
<p class="bibliomixed">[Hunter-] <span class="citetitle"><i class=
"citetitle">Java Servlet Programming</i></span> by Jason Hunter
with William Crawford published by O'Reilly</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
