0

Just have a few questions regarding Java Servlets:

1) What happens when a browser requests a servlet for the first time?

2) Is the the response.setContentType(text,html) the first instruction sent to the browser?

Have been searching the web for answers but not quite sure.

Thanks

millimoose
  • 39,073
  • 9
  • 82
  • 134
  • 1
    Read Head First Servlets and JSP. All those concepts are explained clearly, especially for beginners its too good book – Pradeep Simha Jan 17 '13 at 15:56

2 Answers2

3

No, the first thing to send is the HTTP version :)

   HTTP/1.1 200 OK
   Date: Thu, 17 Jan 2013 21:31:11 GMT
   Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
   Last-Modified: Wed, 01 Jan 2013 21:11:25 GMT
   Content-Type: text/html; charset=UTF-8   

   <HTML>website contents
   here</HTML>

The last line before the content is the content type you are talking about. These headers may occur in different order and there are usually more of them. They order is not strictly defined, maybe the content type would occur before the date. However the HTTP version number and response code (200 - OK in my example) always come first. Read more about HTTP fields here.

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
  • Hi thanks for your answer i was just wondering if you may know what the typical cause of a null pointer exception in servlets would be? – user1344192 Jan 17 '13 at 16:43
  • 1
    @user1344192 The same as in any Java program, dereferencing a null. (There is no typical root cause for that because it depends on the data flow in your entire app.) Fire up a debugger, have it break before the line where the exception occurs, and inspect the expressions in it to see which one is null. – millimoose Jan 17 '13 at 16:46
1

In regards to your question 2):

Servlets don't really sent "instructions" to browsers, they construct a response in some way. They may (but probably don't) send the headers right away, or send the headers when you try to write the body of the response for the first time, when you fill some internal buffer, or they may buffer all of the whole response until you're done. The term for the headers having been sent out is that the response has been "committed", and while you can determine if this has occured for a given response, you can't really prevent it from happening from the API. (I've tried looking at the implementation of Jetty 6 to see what happens but the code is anything but straightforward, which seems to imply container implementations have some leeway here.)

Also, when a servlet is requested for the first time, the servlet is probably instantiated by the container. (Unless it was instantiated before because you set <load-on-startup>1</load-on-startup> in web.xml, or maybe because the container chose to do so - I'm not sure if implementations are allowed to do that.)

millimoose
  • 39,073
  • 9
  • 82
  • 134