clicking on this will visually collapse the text block directly below it

Servlet Tutorial Part 2 - Servlet Basics, September 2002

The Java Http Request / Response Objects

As we discussed in the previous part of this tutorial every interaction between the browser and server is handled with requests & responses. Since everything in Java is handled via objects, both the request sent to the server and the response are handled in their own objects. (If you don't yet understand object oriented programming we suggest you check out our quick object tutorial.) The request object contains all of the information sent from the client's request plus other useful information about the client and this particular request. You will see how to handle these objects, along with some basic code on this part of our servlet tutorial but first let's get to some basic syntax.

Some Basic Syntax

Well let's start at the top. You will need to import the following classes: javax.servlet, javax.servlet.http & java.io. Your class will also need to extend HttpServlet. You should also include an init method (See example below) especially if you need to register variables, database connection pools etc. Note that you will never call the init method, the servlet container will do this the first time the servlet is instantiated. You will then need to override one of the two methods needed to handle Http work, either doPost or doGet. Note that there are other methods for different kinds of work but these two are the most commonly used. the method signature for either of these is as follows:
doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException.
The one you use (doPost or doGet) is determined by how the information is presented to the server or the action attribute of your form. Personally I use doPost exclusively and just call doPost, passing the request & response from inside my doGet like this:

public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(req, res);
}

  So here's what you should have at this point with our basic servlet skeleton. I basically keep one of these around as a template in my editor so I don't have to do it again. Ok we have our skeleton so lets do something with it. Personally I hate that damn Hello World things so let's stay as far away from that as we can! Let's do something a bit cooler that will show some methods of the Request & Response objects.

  I've grabbed a few methods from the ServletRequest interface so we can see this thing in action. Click Here to see them in the code. I think most of these methods are pretty self-explanatory but if you're not sure about them look in the servlet API. Second thing you need to set the content type of the response so the browser knows what the heck is coming in. Oddly enough there is a method of the response class called setContentType("String type") so we set this up with a line like this res.setContentType("text/html"); One warning about forgetting this line in your code, If you don't set the content type in your servlets Netscape will display you source code NOT you finished page! Next we need to get some kind of a writer to print out your page. There are two main writers for this part of servlets: PrintWriter & ServletOutputStream. This is one of those points I see a LOT of people screwing up on. Printwriter is for ASCII based text output (IE: html, text, xml, javascript). ServletOutputStream is for binary data. The ServletOutputStream will work for text based but that's not what it's for! To get a PrintWriter use this line of code: PrintWriter out = res.getWriter();. Now we can print out some goodies to watch this thing tick! Once you have a writer outputting things to the browser is as simple as this: out.print(variable or String);

So click here and add the outlines I've added. Compile this and put it in the appropriate folder in your servlet engine (/webapps/ROOT/web-inf/classes for Tomcat or /doc/web-inf/classes in resin), start your servlet engine, open a browser and type this into the location bar: http://localhost:8080/servlet/FirstCode. or Here is a working example. Notice we do not add any extension to the file name when calling the servlet. The servlet engine knows to find a .class file in the appropriate folder.

OK, so we have output but it's NOT the right way to do it, .... well not exactly. Multiple out.println's have a MAJOR problem. You see Java IO has one basic problem, it can be blocked by other threads. A well known bug in Netscape browsers is caused by this. On pages with large amounts of out.println's Netscape may only display half of the page! Not exactly the results we are looking for! So, how do we solve this issue? It is actually quite simple & the only REAL acceptable way to handle this issue. You simply create a StringBuffer object for any servlet that requires output to the browser, append any text needed to that StringBuffer & then simply use ONE out.println(sb) passing the StringBuffer (I call mine sb) to it. Remember that StringBuffer inherits the toString() method from object automatically so we dont even need that code! Close the out object & you are done! This way all of your output is handled in one output stream that (technically) can't be blocked. So much cleaner, so much more efficient & almost 100% bug free! So here is the code done the right way. I like to put it this way, 3 steps to every servlet:

If you stick to this pattern of handling servlets you really cant go wrong. In other words dont worry about the output until you have EVERYTHING ready for it, don't worry about internal operations until you have the needed input variables! It kind of like putting your clothes on, you wouldn't put your coat on before your shirt would you? And you sure would put on your pants before you put on your underwear, would you .... SO DON'T CODE BACKWARDS!

Page Three - Accepting Parameters

Customer Comments

clicking on this will visually collapse the text block directly below it
I won't go anywhere else. They have gained my trust & confidence and have a great reputation in my book!
Lissa Lee, bathandbodycare.com | More Testimonials >>

Latest Articles / Tutorials

clicking on this will visually collapse the text block directly below it |
Our RSS Article Feed Available as RSS Feed!

Check here often for articles & tutorials that will help make your business grow!

| More Articles & Tutorials >>

Partner Comp. & Friends

clicking on this will visually collapse the text block directly below it