简体   繁体   中英

Why was Servlet.service designed to return void?

In java 7, the Servlet interface is in package "javax.servlet". That interface defines a "service" method that returns void and accepts ServletRequest and ServletResponse as input parameters. Why was it designed to return void instead of ServletResponse? I'm interested in api design and it seems counter-intuitive. But there's probably a good reason for it.

http://docs.oracle.com/javaee/7/api/index.html?javax/servlet/ServletRequest.html

The ServletResponse is not something generated by the servlet.

It is managed by the web application container and injected via a parameter to service , just like the ServletRequest .

Output is created by interacting with this ServletResponse instance (it has methods to retrieve a Writer or OutputStream, and to set headers).

This way, only the container needs to care about managing sockets and other low-level things.

The alternative is to do something like Spring MVC, where the responder method creates and returns some kind of business object (or just a String) to the container. The container then knows how to send this over the wire.

This higher-level API is more convenient for most cases. However, even in Spring MVC, you sometimes need access to the lower-level API, for example to stream large results that you don't want to build in memory (there you get the OutputStream and write to it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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