Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: Build servlet-based enterprise Web applications - JavaWorld - December 1998

Build servlet-based enterprise Web applications - JavaWorld - December 1998

Tutorial Details:

Build servlet-based enterprise Web applications
Build servlet-based enterprise Web applications
By: By Paul Philion
Learn to build better, faster servlets with advanced servlet techniques
he Java servlet architecture provides an excellent framework for server-side processing. Because servlets are written in Java, they can take advantage of Java's memory management and rich set of APIs. Servlets can also run on numerous platforms and HTTP servers without change. Further, the servlet architecture solves the major problem of the CGI architecture: a servlet request spawns a lightweight Java thread, while a CGI request will spawn a complete process. Unless the project has a large budget for high-end Java-based application server projects, servlets offer the best technology to develop server-side components and Web-based applications.
This article, however, is not about the many advantages of the servlet architecture (see Resources for articles covering that); rather, it is about how to use servlets to generate responses efficiently, use less memory in the process, and stream the generated responses back to the client, making response times seem even better. Applying the techniques in this article will allow you to build servlets that can serve more requests and serve them up faster. Based on that foundation, you can build enterprise Web applications that will scale to your needs, run 24x7, and provide the best response times.
To aid my discussion, I use a simple example servlet that counts down from 10 to 1. Each example of the countdown servlet is slightly modified to demonstrate a specific technique. By focusing on the techniques, rather than a fancy example, you'll see how to apply the specific techniques to solve problems in your own servlets.
Note: This article assumes you're familiar with the servlet architecture and have experience writing servlets. See Resources for tutorial information.
Effective servlets
There are two major goals to building servlets for efficient HTML generation. The first goal, especially important for high-volume Web applications, is to carefully control the amount of garbage created during page generation. The more garbage created, the fewer pages generated, and the slower the response time for a request. This bottleneck occurs because the Java VM has to steal cycles to run garbage collection when it should be generating pages. If too much garbage is created, request processing could halt entirely. This is unacceptable for critical Web applications. These problems can be largely avoided using simple ecological techniques: reduce, reuse,and recycle. We'll discuss these techniques in more detail in just a moment.
The second goal of efficient HTML generation is to keep the browser active: the typical Web surfer doesn't have much tolerance for blank gray pages and "waiting for response" messages. The time a Web application spends querying a database or accessing a legacy system is typically the time a user spends staring at a blank page. This can -- and should -- be avoided using servlet response streaming techniques. As we'll see, these techniques dovetail well with the aforementioned ecological techniques, and together they form a foundation for building solid, well-behaved servlets.
Servlet response streaming techniques are also useful for much more than just generating HTML. For servlets, they can be applied when generating XML, JavaScript, GIF or JPEG images, or any other protocol servlets support. In addition, the garbage management techniques we'll cover can be applied to almost any area in Java, especially to applications that must run for an extended period of time.
So let's get started.
Managing garbage
Garbage collection is one of the most attractive features of Java, and servlets can take full advantage of it. Garbage collection still requires a certain amount of overhead, which can be a problem -- especially for server-side applications that generate Web pages dynamically. Server-side applications typically run continuously for extended periods of time. Memory problems that might go unnoticed in client-side applications (like applets or Java GUI applications) could greatly effect the performance of a server-side application in just a few hours of continuous, high-volume operation.
Web page generation requires special consideration, as it uses extensive string manipulation and concatenation. Remember, all String s in Java are immutable, so it's easy to unintentionally create multiple String objects instead of just one. Creating many unnecessary objects can be considered "ecologically unsound" because additional effort -- in the form of CPU cycles -- is required to clean up the garbage. The more garbage created, the more effort required.
By applying our three simple ecological principles -- reduce the number of objects created, reuse the objects that are created, and recycle objects that are no longer needed -- we can develop servlets that are capable of operating for longer periods of time with less overhead. This process results in Web applications that are more robust and better behaved.
Let's take a look at what each of these principles means in practice.
Reduce
One of the most effective ways to avoid the overhead of garbage collection is simply to reduce the number of objects being created. At first this may sound naive, but thinking carefully about how the objects are being used can lead to simplified and more efficient code. Take the following example:
Example 1
public void doGet ( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
res.setContentType( "text/html" );
String html = "Example 1\n";
html += "\n";
html += "

Countdown

\n";
for ( int i = 10; i > 0; i-- ) {
html += "

" + i + "

";
}
html += "

Liftoff

\n";
html += "\n";
PrintWriter out = res.getWriter();
out.println( html );
out.close();
}
Note: This example, while slightly contrived to demonstrate the point, represents what a servlet might look like if ported directly from a Perl CGI script.
The above implementation will create 14 String s and 13 StringBuffer s. Most of these objects are created inside the for loop; each time through the loop a String and a StringBuffer pair are created. A much cleaner way to implement the same method would be to simply write the output directly to the ServletResponse 's PrintWriter :
Example 2
public void doGet ( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
res.setContentType( "text/html" );
PrintWriter out = res.getWriter();
out.println( "Example 2" );
out.println( "" );
out.println( "

Countdown

" );
for ( int i = 10; i > 0; i-- ) {
out.print( "

" );
out.print( i );
out.println( "

" );
}
out.println( "

Liftoff

" );
out.println( "" );
out.close();
}
This example generates the same HTML output without creating any objects at all. The difference here is that all output is written directly to the PrintWriter , which does not require creating any intermediate objects. Because fewer objects are created and less memory is used, garbage collection is needed much less frequently. This means more pages can be generated -- and more requests served -- with the same resources.
You can download all the examples in this article from Resources . Each is contained in fully functional servlets, named Example1.java, Example2.java, etc. The actual source code contains comments about the servlet functions, but the examples are intended for use with this article.
Reuse
It isn't always reasonable, or even possible, to simply write all output directly to the PrintWriter provided in the ServletResponse . For example, in situations where a portion of the HTML is going to be generated before the response is served, it makes sense to use some sort of buffering mechanism. As I demonstrated in our first example, the String object can't be used as a buffer. Behind the scenes, the Java compiler really creates a StringBuffer and a String for each line of code that does any string manipulation. This doesn't help reduce the number of objects being created.
A StringBuffer is the best way to manipulate string values. You can create a StringBuffer , use it to concatenate several String s or other values (including primitives), and then convert it into a single String . Further, the String and StringBuffer will work together, sharing the same memory until the StringBuffer is modified. The following example shows how you can use a StringBuffer instead of String concatenation:
Example 3
public void doGet ( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
res.setContentType( "text/html" );
StringBuffer buffer = new StringBuffer( 1024 );
buffer.append( "Example 3" );
buffer.append( "" );
buffer.append( "

Countdown

" );
for ( int i = 10; i > 0; i-- ) {
buffer.append( "

" );
buffer.append( i );
buffer.append( "

" );
}
buffer.append( "

Liftoff

" );
buffer.append( "" );
PrintWriter out = res.getWriter();
out.println( buffer.toString() );
out.close();
}
In this example, the StringBuffer isn't altered after the call to toString() , so the char array backing the StringBuffer is never copied, which reduces the memory use. The countdown loop in this example demonstrates yet another memory reduction technique. It could have been written
buffer.append( "

" + i + "

" );
but this would have resulted in a String and StringBuffer being created for each pass through the loop.
Recycle
One final note about managing garbage: the garbage collector can't collect garbage it thinks is still being used. Make sure at the end of your page-generation process that all unneeded objects are no longer referenced. If th


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Build servlet-based enterprise Web applications - JavaWorld - December 1998

View Tutorial:
Build servlet-based enterprise Web applications - JavaWorld - December 1998

Related Tutorials:

Use Web services to integrate Web applications with EISs
Use Web services to integrate Web applications with EISs
 
Ilog JRules 4.0: Working by the rules
Ilog JRules 4.0: Working by the rules
 
Rumble in the jungle: J2EE versus .Net, Part 1
Rumble in the jungle: J2EE versus .Net, Part 1
 
Business process automation made easy with Java, Part 1
Business process automation made easy with Java, Part 1
 
Best tools for mobile application development
Best tools for mobile application development
 
Update distributed applications
Update distributed applications
 
The J2EE 1.4 Tutorial
The J2EE 1.4 Tutorial is a guide to developing enterprise applications for the Java 2 Platform, Enterprise Edition (J2EE) version 1.4. Here we cover all the things you need to know to make the best use of this tutorial.
 
Put JSF to work
Build a real-world Web application with JavaServer Faces, the Spring Framework, and Hibernate Summary Building a real-world Web application using JavaServer Faces is not a trivial task. This article shows you how to integrate JSF, the Spring Framewor
 
Turn EJB components into Web services
Summary Web services have become the de facto standard for communication among applications. J2EE 1.4 allows stateless Enterprise JavaBeans (EJB) components to be exposed as Web services via a JAX-RPC (Java API for XML Remote Procedure Call) endpoint, al
 
Using Timers in J2EE Applications
Using Timers in J2EE Applications Job scheduling is nothing new--most enterprise applications require the scheduling of tasks and activities. For example, your application may need a timer service to run a business process once a day, or to clean up a te
 
Networking our whiteboard with servlets.
Find out how to easily replace the RMI and sockets networking layers with servlets.
 
FreeMarker FreeMarker 2.3.1 an open-source HTML template engine.
FreeMarker provides an easy way to get data from Java servlets into Web pages, and helps you keep graphic design separate from application logic. To use it, you encapsulate HTML in templates.
 
Service Orchestration - Cornerstone for Building Service-Oriented Architecture
This Web Cast explains the Service-Oriented Architecture (SOA). Service-oriented architecture is rapidly becoming the cornerstone for enterprise infrastructure, bringing cost reductions and increasing IT and business responsiveness.
 
Struts, JavaServer Faces, and Java Studio Creator:
The Evolution of Web Application Frameworks Sun Microsystems' Craig McClanahan, the creator of the Apache Struts Framework, co-specification lead for JavaServer Faces 1.0, and prime architect for Sun Java Studio Creator's new release, explains all three.
 
Open Source Web Frameworks in Java
Open Source Web Frameworks in Java Open Source Web Frameworks in Java Struts Struts Frame work is the implementation of Model-View-Controller (MVC) design pattern for the JSP. Struts is maintained as a part of Apache Jakarta project and is open
 

Free Web Site Hosting Services Below is the listing of the hosting providers providing free web hosting services. These services helps you building your sites even if you have no experience in HTML writing. Zero
 
Introduction To Enterprise Java Bean(EJB). WebLogic 6.0 Tutorial.
Introduction To Enterprise Java Bean(EJB). WebLogic 6.0 Tutorial. Welcome to EJB Section (Learn to Develop World Class Applications with Enterprise Java Beans) (Online WebLogic 6.0 Tutorial) Introduction To Enterprise Java Bean(EJB) Enterprise
 
Building Web Application With Ant and Deploying on Jboss 3.0
Building Web Application With Ant and Deploying on Jboss 3.0 Building Web Application With Ant and Deploying on Jboss 3.0 Previous Tutorial Index Next In this lesson I will show you how to build you web application and install on the Jboss 3.0
 
developing a Session Bean and a Servlet and deploy the web application on JBoss 3.0
developing a Session Bean and a Servlet and deploy the web application on JBoss 3.0 Writing Stateless Session Bean and Calling through Servlet Previous Tutorial Index Next In this lesson I will show you how to develop a Stateless Session Bean and
 
NetBeans IDE 4.1
Out-of-the-box support for J2EE 1.4 and Web Services. Check out what early access release 2 can do for you!
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.