Micarle
Micarle

Reputation: 141

Why RequestBody in HttpServletRequest is an InputStream?

I know that in BIO, web container receives the request and wrap it in a HttpServletRequest object, and We can get Header and other stuff from it. I think the HTTP Message has been copied to User-space. But why the request body is still an inputstream ? Can anybody explain that? Thanks a lot!

Upvotes: 1

Views: 1059

Answers (1)

lance-java
lance-java

Reputation: 27996

HttpServletRequest is an interface from the servlet specification. There are many servlet container implementations including jetty, tomcat and websphere to name a few. Each has its own implementation of HttpServletRequest.

Using an InputStream gives freedom to the servlet implementation to source the request body value from wherever it likes. One implementation might use a local file and FileInputStream, another may have a byte array in memory and use ByteArrayInputStream, another might source from a cache or database etc.

Another benefit of InputStream over a byte array is that you can stream over it only holding a small chunk in memory at a time. There's no requirement to have a large byte array (eg gigabytes) in memory all at once.

Imagine a video sharing site where each user can upload 1GB videos. If the servlet spec were to impose byte array instead of InputStream then a server with 8GB of ram could only support 8 concurrent uploads. With InputStream you can have a small buffer of ram for each upload so could support hundreds/thousands of concurrent 1GB uploads

Upvotes: 2

Related Questions