Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
}
like image 234
havstein Avatar asked Dec 05 '22 04:12

havstein


1 Answers

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.

like image 162
BalusC Avatar answered Feb 24 '23 03:02

BalusC