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.