开发者

Should a servlet explicitly return at the end of doGet/doPost?

Is there any difference betwe开发者_开发知识库en explicitly returning at the end of doGet or doPost-methods, and just letting the method return "by itself"?

public void doGet(HttpSerlvetRequest req, HttpServletResponse resp) {
    <my code here>
    return;
}

public void doGet(HttpSerlvetRequest req, HttpServletResponse resp) {
    <my code here>
}


There are however cases where you see the return statement in a servlet method which might be at first glance confusing for starters. Here's an example:

protected void doPost(request, response) {
    if (someCondition) {
        response.sendRedirect("page");
        return;
    }
    doSomethingElse();
    request.getRequestDispatcher("page").forward(request, response);
}

Here the return statement is necessary because calling a redirect (or forward) does not cause the code to magically jump out of the method block as some starters seem to think. It still continues to run until the end which would cause an IllegalStateException: response already committed at the point when the forward is called.


No. As a regular void method, it does not require a return


Utterly unnecessary; doesn't add any style points, either.


There is no difference at all, a return is implicit at the end of a method.


No difference at all, the return statement is unnecessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜