22
Fri, Nov
1 New Articles

Java Journal: Servlets

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
So you want to go wading in the Java Web development ocean--just enough to get your feet wet but not enough to get sucked out to sea in a riptide of XML configuration files or get eaten by application server installation sharks. Well, you have come to the right beach. In this month's Java Journal, I'll show you a simple way to set up an environment where you can play with servlets without having to risk the terrors of the deep.

First, let me explain what servlets really are. Most people associate servlets with Web servers; in fact, Sun's own definition of a servlet is a way of "extending the functionality of Web Servers." While this is true, it is also a little misleading and puts servlets in a smaller box than I like, but more on that later. So for my definition of a servlet, I'm going to go with this: "A servlet is the implementation of a specific Java interface called GenericServlet that has an associated input (or request) object and an output (or response) object." GenericServlet is part of the javax.servlet package that is part of Sun's Java 2 Enterprise Edition (J2EE), but it can also be used as an extension to Sun's Java 2 Standard Edition (J2SE) without having all the other extensions--such as Enterprise Java Beans (EJBs)--that come along with the full-blown J2EE package. Or more simply put, a servlet is something you make a request of and then receive a response from. Since the javax.servlet package already has a concrete implementation of the GenericServlet interface for handling HTTP requests, I will use it for my example, but keep in mind that this is only one of any number of possible concrete implementations of GenericServlet. It just happens to be the easiest and most compelling one to provide examples for.

HttpServlets allow you to make HTTP requests--such as GETs and POSTs--that return dynamic, Java-generated HTML responses. In other words, HttpServlets allow you to embed HTML in Java source code. HttpServlets, like all servlets that implement GenericServlet, live in Web containers that are simply the wrapper around the servlet that allows them to accept requests from and send responses to a Web server. Any J2EE-compliant application server functions as a Web container for servlets, but for the purposes of this discussion, I will look at another implementation of servlet Web containers called Tomcat. Tomcat is one of several projects hosted by Jakarta at Apache. Tomcat provides Web containers for both servlets and JavaServer Pages (JSPs). Although it is part of the Sun J2EE reference implementation, it does not provide containers for EJBs and thus is not a J2EE platform on its own. I chose Tomcat for my examples because it is very stable and mature as well as seamlessly integrated with Apache's Web server, but the best reason of all is that it's free.

What You Will Need

To try the example I'm going to present here, you will need two pieces of software: Tomcat and a current Java Developer Kit (JDK) from Sun. Any version 1.2 or higher of the JDK should work, although I used 1.4 when developing my example. You can get the JDK 1.4 here. Just accept all the defaults on the installers. You can get a copy of Apache's servlet/JSP container called Tomcat 4.0.4 from here. Install it and accept all the defaults. The Tomcat installer will put convenience shortcuts on your Start menu under Apache Tomcat for starting and stopping the server. Start the Tomcat server, which by default will be listening on port 8080. You can test that Tomcat is installed correctly by pointing your Web browser to http://localhost:8080/, which should take you to a page congratulating you on your successful installation of Tomcat. There are some example servlets that you can link to off of this page, but I always find I learn the most by creating one of my own.

Configuration

Before you can write your servlet, you need to set up a new CLASSPATH entry and let Tomcat know where you are going to store your servlet. For this example, you will need several classes from the servlet.jar library that is included as part of Tomcat. If you accepted all the defaults on your Tomcat installation, you will add C:Program FilesApache Tomcat 4.0commonlibservlet.jar to your CLASSPATH. Next, set up a home for your servlet in the Tomcat tree by adding a folder called servletExample under Apache Tomcat 4.0webapps. Then, create a folder called WEB-INF and put it inside your new servletExample folder. Now, make one last folder called classes and put it in WEB-INF. This will be the folder in which you store the .class file for your servlet. Just one last step: You need to let Tomcat know where to look for your servlet when it gets a request. So look for the server.xml file in Apache Tomcat 4.0conf and add the following entry somewhere near the other context declarations:


  docBase="C:Program FilesApache Tomcat 4.0webappsservletExample">

The Good Stuff

Now you are ready for your first servlet, which simply returns a snippet of HTML-formatted text. See Figure 1.

// ServletJJ.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

public class ServletJJ extends HttpServlet
{
  public void doGet(HttpServletRequest request, 
                  HttpServletResponse response)
            throws ServletException, IOException
    {
      response.setContentType("text/html");
      PrintWriter out = new PrintWriter(response.getOutputStream());
      out.println("");
      out.println("");
      out.println("Hello from the Java Journal servlet");
      out.println("")
      out.println("");
      out.flush();
    }
}


Take a look at the code. It begins with the obligatory set of imports. Note that I did not use .* imports--this way, you can tell which package each class is in. The java.io classes are part of J2SE, but all the javax.servlet classes are from Tomcat. Next, I declared the new servlet class, which extends HttpServlet, and overrode the doGet() method that it inherits. For this example, I ignored the request object that is passed in and provisioned the response class with a contentType and an outputStream with some simplistic HTML. That's all there is to it; Tomcat handles all the details.

Now, compile the example and move the resulting ServletJJ.class file to the servletExample WEB-INFclasses directory that you created earlier. If Tomcat is currently running, stop it and restart it using the shortcuts on the Start menu. Then, start up your Web browser and enter http://localhost:8080/test/servlet/ServletJJ. You should get back a Web page containing the message from the source code. Note that this URL may not look very intuitive. The localhost:8080 is of course port 8080 on your local machine. The /test directory is from the server.xml docBase that you set earlier. The /servlet was preconfigured in Tomcat's default .xml to point to the WEB-INF/classes directory under a doc base. As a general rule, servlet containers such as Tomcat hide what is in their WEB-INF directories from direct access. So if you were to try to go to http://localhost:8080/test/WEB-INF/classes/ServletJJ, you would get a 404 error. This feature helps keep your servlets secure.

This example shows the entry point for http GETs. There is also a corollary entry point for POSTs called doPost(), which takes the same arguments as the doGet(). So next, try implementing something dynamic--like returning a timestamp--or go all out and connect to your favorite database and grab some data. Just send all your output to the PrintWriter, and it will show up on the Web page.

So Why Use Servlets?

Servlets are generally used as a replacement for traditional CGI programming. Although servlets have a number of advantages over CGIs, the most important to me are that they are easy to extend, secure, easy to debug, and portable. Servlets are easy to extend because they have the power of all the Java APIs behind them. So whether you need to retrieve data from the database, use a library of HTML tags or send email, chances are that there is already a Java API written and waiting for you. Since servlets execute within a Web container such as Tomcat, which restricts direct access to your servlets .class files, your first line of security is already provided for you. Many IDEs have built-in debuggers that allow you to step right into your servlet code, something I've never been able to do when trying to debug a CGI. The final advantage, which is more or less synonymous with Java, is portability. This is especially important when developing servlets because you can develop and test your servlet on your laptop and not have to worry about whether it will run differently on your production enterprise servers.

So Why Not Use Servlets?

Although servlets do provide a lot of great features, most people use HttpServlets to provide dynamic Web pages by embedding HTML in their Java code, as in the example. For small projects and prototyping, servlets are great, but because the Web pages are rendered at runtime, you cannot leverage high-end HTML editors and you often wind up with HTML in many places in your code where it doesn't belong. Also, making style changes to your site can be painful because the HTML may be spread over any number of source files. So Sun came up with two competing technologies: JavaServer Pages (JSPs) and Java Web Services. By invoking Java methods from within HTML, JSPs allow us to reverse the embedding so that we can take full advantage of Web authoring tools. Java Web Services are the future of servlets; they allow servlets to work together as an integrated, yet loosely coupled, system. I will take a look at both JSPs and Java Web Services in upcoming Java Journals.

Conclusion

Servlets are the easiest way to get yourself some experience doing Web programming, and you don't need a full-blown, expensive J2EE application server to get started. Tomcat is a good tool to practice writing servlets with and is easy to configure. Although servlets may not be the best solution for generating dynamic Web pages, they are a fundamental piece of Java Web Services and a good place to start getting your feet wet.

Michael J. Floyd is an Extreme Programmer and the Software Engineering Technical Lead for DivXNetworks. He is also a consultant for San Diego State University and can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..

Michael Floyd

Michael J. Floyd is the Vice President of Engineering for DivX, Inc.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: