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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With