hav*_*ein 4 java servlets return
在doGet或doPost方法结束时显式返回,只是让方法"自行返回"之间有什么区别吗?
public void doGet(HttpSerlvetRequest req, HttpServletResponse resp) {
<my code here>
return;
}
public void doGet(HttpSerlvetRequest req, HttpServletResponse resp) {
<my code here>
}
Run Code Online (Sandbox Code Playgroud)
Bal*_*usC 11
但是,有些情况下,您可以return在servlet方法中看到该语句,这对于初学者来说可能会让人感到困惑.这是一个例子:
protected void doPost(request, response) {
if (someCondition) {
response.sendRedirect("page");
return;
}
doSomethingElse();
request.getRequestDispatcher("page").forward(request, response);
}
Run Code Online (Sandbox Code Playgroud)
这里的return语句是必要的,因为调用重定向(或转发)不会导致代码神奇地跳出方法块,正如一些初学者似乎认为的那样.它仍然继续运行直到结束,这将导致IllegalStateException: response already committed在调用前锋时.
| 归档时间: |
|
| 查看次数: |
3686 次 |
| 最近记录: |