简体   繁体   中英

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

Is there any difference between 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.

不。作为常规的void方法,它不需要return

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

根本没有区别,返回隐含在方法的末尾。

没有任何区别,返回声明是不必要的。

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