简体   繁体   English

Java Servlet将数据传输到浏览器

[英]Java Servlets transmitting data to browser

Just have a few questions regarding Java Servlets: 只是对Java Servlet有几个问题:

1) What happens when a browser requests a servlet for the first time? 1)当浏览器第一次请求servlet时会发生什么?

2) Is the the response.setContentType(text,html) the first instruction sent to the browser? 2)response.setContentType(text,html)是发送给浏览器的第一条指令吗?

Have been searching the web for answers but not quite sure. 一直在网上寻找答案,但不确定。

Thanks 谢谢

No, the first thing to send is the HTTP version :) 不,要发送的第一件事是HTTP版本:)

   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. 但是,HTTP版本号和响应代码(在我的示例中为200-确定)始终排在最前面。 Read more about HTTP fields here . 在此处阅读有关HTTP字段的更多信息。

In regards to your question 2): 关于您的问题2):

Servlets don't really sent "instructions" to browsers, they construct a response in some way. Servlet并没有真正向浏览器发送“指令”,而是以某种方式构造了响应。 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. 标头已发出的术语是响应已“提交”,尽管您可以确定给定响应是否已发生,但您无法真正阻止它从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.) (我尝试查看Jetty 6的实现,以查看会发生什么,但是代码并非一帆风顺,这似乎暗示着容器的实现还有一些余地。)

Also, when a servlet is requested for the first time, the servlet is probably instantiated by the container. 同样,当第一次请求servlet时,该servlet可能由容器实例化。 (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.) (除非之前已实例化,否则是因为您在web.xml设置了<load-on-startup>1</load-on-startup> ,或者可能是因为容器选择了这样做-我不确定是否允许实现去做。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM