Get started with Java servlets

ANALYSIS
Java servlets offer a simple way to extend and enhance Web server functionality. They're platform-independent, so you can select the best method for your particular servers or platform. In addition, servlets use the entire Java repertoire of APIs. Our focus here will be on how the servlet classes that the Java platform provides enable you to build Web applications using the same object-oriented techniques used in a fat client environment. Introducing servlets The Java servlet architecture facilitates server-side processing using the Java programming language. Since servlets are written in Java, they empower server-side developers with all of Java's benefits and APIs, including the ability to write a servlet once and run it on any Java-enabled server platform. Servlets offer a major leap forward from traditional CGI development. Each servlet request is handled by a thread instead of an entirely new process, as is the case with traditional CGI implementations. Servlets are developed using the Java Servlet API that is packaged in the namespaces javax.servlet and javax.servlet.http. Within these two packages are classes, interfaces, and frameworks that encapsulate functionality and properties for all of the HTTP protocol's request/response communications, including session handling, POST requests, and GET requests. Since servlets are written using the Java programming language, all the facilities that a Java class enjoys are also available to the servlet environment. Certainly one of the most important and useful of these is the ability to access a SQL database using the Java Database Connectivity (JDBC) API. Servlet architecture The featured component created with the servlet API is the servlet itself. A servlet is an object that extends either the javax.servlet.GenericServlet class or the javax.servlet.http.HttpServlet class. The javax.servlet.GenericServlet class defines methods for building generic, protocol-independent servlets. The javax.servlet.http.HttpServlet class extends this class to provide HTTP-specific methods. The diagram in Figure A illustrates the hierarchy of a typical HTTP servlet and the relationships and functionality exposed by the classes in the hierarchy.

Figure A
Class hierarchy
As you can see, the GenericServlet class defines generic server-side operations; the HttpServlet extends this to define HTTP-specific operations; and application-specific servlets extend this to provide application-specific operations. We will be referring to servlets created for the HTTP environment throughout this article. Client-servlet interaction In a typical HTTP servlet environment, a user instigates a session with a servlet by directing a Web browser at a URL that loads a servlet on a server. The browser then communicates a request to the servlet over a socket on port 80. The servlet, listening on port 80, fields the request, extracts any parameters or data from the request, and dispatches the application flow to the appropriate business-logic component to execute one or more tasks. Once the business-logic component has finished executing, it passes its results back to the servlet to be formatted as HTML and passed back to the user's browser. Figure B illustrates the typical interaction between a browser, a servlet, and a business-logic component.

Figure B
Servlet example Listing A provides the code for a simple HTTP servlet. In our example, I will assume that all requests are HTTP GET requests. The GenericServlet and the HttpServlet both expose a method called service, which can be used as the point to intercept the request from a client. The HttpServlet extends this by diagnosing the HTTP request and dispatching it to HTTP-specific methods, such as doPost and doGet. Since all requests are HTTP GET requests, I need to focus only on the doGet method. Here are some points to notice in this example:
  • SimpleServlet extends the javax.servlet.http.HttpServlet class.
  • SimpleServlet overrides the doGet method in the javax.servlet.http.HttpServlet class to field the HTTP request, dispatch the business logic, and formulate the response.
  • The HTTP request is encapsulated in an object of type javax.servlet.http.HttpServletRequest.
  • The HTTP response is encapsulated in an object of type javax.servlet.http.HttpServletResponse.
  • We can use a standard java.io.PrintWriter to inject the response data into the HTTP stream.
Using the Java servlet API, you can enjoy all the benefits afforded by the programming language and carry these benefits into the traditional CGI environment. The classes provided by the servlet API allow us to interact with HTTP-enabled applications using most of the same techniques and experiences learned from programming in a desktop environment.
Have your say instantly in the
Tech Update forum. Find out what's where in the new Tech Update with our
Guided Tour. Let the editors know what you think in the
Mailroom.

Post your comment

In order to post a comment you need to be registered and logged in.

You can also log in with Facebook. Log in or create your ZDNet UK account below

  • Login

Will not be displayed with your comment

By signing up for this service, you indicate that you agree to our Terms and Conditions and have read and understood our Privacy Policy. Questions about membership? Find the answers in the Community FAQ

Get ZDNet UK's daily newsletter

Enter your email address to sign up

ZDNet UK Live

GHar123

I totally dislike pirating of works, I fear that artists will be deterred from creating works if they think that they are going to get ripped off....

1 hour ago by GHar123 on ACTA stumbles in Germany
JCB33

How dare film makers, artists or anybody that invests in creativity stop us pirating their works for free. I want to be able to walk into my local...

7 hours ago by JCB33 on ACTA stumbles in Germany
Moley

@GrueMaster. I prefer horses for courses rather than one size fits all. I, and I suspect most other computer users, do not really wish to have...

9 hours ago by Moley on A tale of two distros: Ubuntu and Linux Mint
greycynic

The product that scares me every time I have to use it is the Office 2007 version of Excel. The first bug that I found was applying the median...

9 hours ago by greycynic on Ten flawed products that derail productivity
GrueMaster

Nice review and very informative. One thing I'd like to add (in reply to whs001's 1st question), the main reason to have the same interface from...

10 hours ago by GrueMaster on A tale of two distros: Ubuntu and Linux Mint
Frederick Wrigley

I'be been using Mint 12 since the RC came out, and I am far more happy with the Cinnamon, the Mate, and, yes (with extensions), theGnome 3...

11 hours ago by Frederick Wrigley via Facebook on A tale of two distros: Ubuntu and Linux Mint
bdantas

Excellent article. One small correction, though--although a fresh installation of Linux Mint 12 will, indeed, provide the user with a version of...

12 hours ago by bdantas on A tale of two distros: Ubuntu and Linux Mint
Alan Ralph

In related news, the ISPs club together to get the members of the Home Affairs Select Committee (ya goofed on that part, ZDNet UK) copies of "The...

12 hours ago by Alan Ralph via Facebook on MPs urge ISPs to take down terrorist material
Alan Ralph

In related news, the ISPs club together to get the members of the Home Affairs Select Committee (ya goofed on that part, ZDNet UK) copies of "The...

12 hours ago by Alan Ralph via Facebook on MPs urge ISPs to take down terrorist material
Moley

For Gnome 2 die-hards, it is possible to add icons to the bottom panel (or top top panel, if you prefer) which provide the exact Gnome 2...

13 hours ago by Moley on A tale of two distros: Ubuntu and Linux Mint
ramwellian

Your comments would seem pretty naive and immature. Your 'solution' appears to be, "gee, let's all just give in to the hackers and give them...

13 hours ago by ramwellian on Cloud computing security: no more oxymoron?
BugStalker

"Interesting thought ... If you installed Win7 as a dual boot on a machine that previously only had Linux, and it wrecked your Linux installation,...

14 hours ago by BugStalker on Windows 7 Declares War on GRUB
whs001

This is an excellent summary of Ubuntu and Mint and the interface differences between them. Most such articles take a very partisan position for...

14 hours ago by whs001 on A tale of two distros: Ubuntu and Linux Mint
Moley

@ewallace. Not so clear. Anyone can obtain the text, for example from here http://www.ustr.gov/webfm_send/2379. I support ACTA so long as it and...

14 hours ago by Moley on ACTA: Facts, misconceptions and questions
45283

I think WinRT is fantastic. I just wish it was an option for people that didn't want to go through Microsoft's App Store with its attendant...

17 hours ago by 45283 on Why Windows 8 needs architectural hygiene for WOA
Burn-IT

Nine people? £30m? Who's back pocket is that lot going in? And IF they say it is for new buildings, what about all the ones the government has...

18 hours ago by Burn-IT on Police set to launch three £30m e-crime hubs
ewallace

Just to be clear, nobody knows what is in the text of ACTA, here is a photograph of the text of ACTA http://twitpic.com/8h9iju as submitted to the...

18 hours ago by ewallace on ACTA: Facts, misconceptions and questions
fgvrg56

Unfortunately main issue is that ASUS is refusing to accept that they make some mistake on this version of asus Transformer prime. 1 - GPS sensor...

20 hours ago by fgvrg56 on Asus Eee Pad Transformer Prime Wi-Fi & GPS problems?
Ben Woods

@Marcus A fair question. Just talked with Archos which said it was working on an announcement for next week....

21 hours ago by Ben Woods on Archos confirms G9 Ice Cream Sandwich update schedule
Marcus Karlsson

Any update on this, considering the claimed "first week of February"?

22 hours ago by Marcus Karlsson via Facebook on Archos confirms G9 Ice Cream Sandwich update schedule

Latest in Application Development