Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a Servlet's doGet()-method have the response as parameter instead of return value?

I never questioned this before, but why

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{}

instead of

public HttpServletResponse doGet(HttpServletRequest request)
    throws ServletException, IOException{}

?

Wouldn't the second version make semantically more sense?

like image 218
Lester Avatar asked Mar 22 '23 13:03

Lester


1 Answers

HttpServletResponse is a rather complicated class, requiring you to know about connection sockets and such. If you had to return one, most of the code would be the same boilerplate to construct it. Instead the servlet container does this work for you, giving you a ready-to-use object with a variety of useful working methods.

Now the next question is why did they decide to make HttpServletResponse a complicated object and not just have you return a simple POJO. Well for one, that architecture would not allow you do do any streaming responses where you start writing before you have all the data.

like image 53
OrangeDog Avatar answered Apr 06 '23 02:04

OrangeDog