Reputation: 41
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
Upvotes: 0
Views: 175
Reputation: 39950
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.)
Upvotes: 1
Reputation: 21728
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.
Upvotes: 3