Java Servlets
The Servlet interface provides the foundation for all servlets. All servlets must either implement this interface or be extensions of a class which implements it. The Servlet package provides a class called HttpServlet which implements the Servlet interface, so as a servlet developer, much of the work is done for you. The Servlet interface allows the creation of generic servlets, but we will only look at how to create servlets that act as CGI scripts. For this, all you have to worry about is the HttpServlet class.
Let's step through the code of the simple servlet shown in Listing 1 to see how it works. This servlet overrides the doGet method provided by the HttpServlet class. doGet is called when a client makes a GET request to the servlet. Here we have the servlet respond with a simple web page that gives the standard “Hello World” message. The doGet method gets two objects, HttpServletRequest and HttpServletResponse, which encapsulate information that allows the servlet to obtain information from and communicate with the client. For example, the HttpServletResponse object contains a PrintWriter object that can be used to send information back to the client. In this example, we use it to send our “Hello World” message back to the client. We also use the setContentType method of the HttpServletResponse object to inform the client that it will be receiving text/HTML data from the servlet.
Now that we've seen a simple example, let's step back a bit and look at how HTTP Servlets work. Servlets extending the HttpServlet class handle all of their client requests through its service method. The service method understands standard HTTP requests, and calls appropriate methods to handle each request. In the example above, the service would recognize the GET request and call the doGet method accordingly. Similarly, doPost, doPut and doDelete methods are provided to handle other types of HTTP requests.
A servlet's life begins when the servlet's init method is called. The web server calls the init method when it loads the servlet, but before any client requests are handled. The init method is called only once when the servlet is loaded. So, if you need to perform any initialization before your servlet starts handling requests, overload the init method as follows:
public void init(ServletConfig config) throws ServletException {
super.init(config);
...
}
The init method is passed an object which contains configuration information about the servlet. It is a good idea to store this object to make it available if the client needs it. The easiest way to do this is to call the init method of superclass and pass the ServletConfig object to it. One final tip regarding the initialization of servlets: if your initialization fails and the servlet can't handle client requests, throw an UnavailableException. After initialization takes place, the servlet is up and the service method handles client requests.
Finally, when the servlet is unloaded from the web server, its destroy method is called. The web server waits until all service methods are finished or a certain number of seconds have passed (whichever comes first) before calling the destroy method. In the case of long-running service methods, it is possible the destroy method will be called before all service calls have been completed.
This situation can be handled with a few additional methods and variables. First, create a variable that keeps track of how many service methods have been called and provide synchronized methods for increasing and decreasing the counter, as well as one to return the value of your service counter.
public MyServlet extends HttpServlet {
private int numServices = 0;
protected synchronized void enterService() {
numServices++;
}
protected synchronized void exitService() {
numServices-;
}
protected synchronized int serviceCount() {
return numServices;
}
}
Now, that we have these counters, we need to modify the service method to increment and decrement them accordingly. This is done by adding a call to the enterService method at the top of the service method, calling the service method of the superclass to handle the real work and then decrementing the counter by calling the exitService method.
protected void service(HttpServletRequest req, HttpServletResponse
resp)
throws ServletException, IOException
{
enterService();
try {
super.service(req, resp);
} finally {
exitService();
}
}
Next, a flag is needed to determine if the servlet is in the
process of shutting down. To accompany this flag, use accessor
methods to set the flag and return its value.
MyServlet continued {
private Boolean exiting;
protected setExiting(Boolean flag) {
exiting = flag;
}
protected Boolean isExiting() {
return exiting;
}
}
Now the destroy method should first check if any services haven't
completed, then loop until all services are finished.
public void destroy() {
if (serviceCount() > 0) {
setShuttingDown(true);
}
while(serviceCount() > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
}
}
}
Finally, modify any of your methods that may run for a long time to
check if the servlet is shutting down, and act accordingly.
public void doPost(...) {
/* You could do something like this or put
* the check into a loop
* that takes a long time */
if(!isExiting) {
...
}
}
So there you have it: a quick introduction to getting servlets up
and running on your Linux box and writing some simple ones. If you
want to learn more about writing servlets, books are available
which cover them in depth. I would also recommend looking at the
Java Tutorial, available on Sun's web site; it contains a nice
introduction to servlets I used when I started learning about them.
Doug Welzel recently finished up his undergraduate work at Carnegie Mellon University and is continuing his graduate studies. He has been using Linux throughout his career at CMU and welcomes your comments at welzel@andrew.cmu.edu.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
- Using Salt Stack and Vagrant for Drupal Development
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- New Products
- RSS Feeds
- New Products
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




3 min 7 sec ago
6 hours 17 min ago
11 hours 56 min ago
17 hours 55 min ago
18 hours 18 min ago
18 hours 28 min ago
18 hours 32 min ago
19 hours 2 min ago
21 hours 54 min ago
22 hours 29 min ago