为什么Servlet的doGet()方法将响应作为参数而不是返回值? [英] Why does a Servlet's doGet()-method have the response as parameter instead of return value?

查看:233
本文介绍了为什么Servlet的doGet()方法将响应作为参数而不是返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前从未质疑过,但为什么

I never questioned this before, but why

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

而不是

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

第二个版本不会在语义上更有意义吗?

Wouldn't the second version make semantically more sense?

推荐答案

HttpServletResponse 是一个相当复杂的类,需要您了解连接套接字等。如果你必须返回一个,那么大多数代码都是相同的样板来构造它。相反,servlet容器为你工作,为你提供一个随时可用的对象,其中包含各种有用的工作方法。

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.

现在接下来的问题是他们为什么这样做了决定使 HttpServletResponse 成为一个复杂的对象而不只是让你返回一个简单的POJO。好吧,那个架构不允许你在你拥有所有数据之前开始写任何流式响应。

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.

这篇关于为什么Servlet的doGet()方法将响应作为参数而不是返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆