問題描述
我正在開發(fā)基于 geo-location
呈現(xiàn)內容的 servlet 頁面,我想同時使用 sendRedirect
和 forward
;例如;您從 France
瀏覽 example.com/aPage.jsp
;首先,我希望 servlet 將您重定向到 example.com/fr/aPage.jsp
,然后將您轉發(fā)到 resources
頁面.
I'm working on servlet page that renders content based on geo-location
, and I want to use both sendRedirect
and forward
together; e.g; you browse example.com/aPage.jsp
from France
; first I want the servlet to redirect you to example.com/fr/aPage.jsp
and then forward you to the resources
page.
這就是我的 servlet 中的內容:
This is what I have in my servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
....
response.sendRedirect(REDIRECT_URL_BASED_ON_GEO);
// after redirect forward the resources page
RequestDispatcher view = request.getRequestDispatcher(RESOURCES_PAGE);
view.forward(request, response);
...
}
但我明白了:
java.lang.IllegalStateException: Cannot forward after response has been committed
我知道錯誤出現(xiàn)是因為我不能同時使用 sendRedirect
和 forward
一個又一個,但我不知道如何在沒有這個的情況下實現(xiàn)我想要的(如上所述).
I know the error appears because I can't use both sendRedirect
and forward
one after another, but I don't know how to achieve what I want (as described above) without this.
有什么幫助嗎?
推薦答案
response.sendRedirect(REDIRECT_URL_BASED_ON_GEO);
// after redirect forward the resources page
在那一行之后,您的回復開始寫入 clinet.
After that line , Your response start writing to clinet.
您正在嘗試向其中添加其他數(shù)據(jù).
And you are trying to add additional data to it.
服務器已經(jīng)完成響應頭的寫入,并且正在寫入內容的正文,以及您嘗試在標題中寫入更多內容的點 - 當然它不能倒帶.
The server has already finished writing the response header and is writing the body of the content, and which point you are trying to write more to the header - of course it cant rewind.
所以,處理 servlet 時的拇指規(guī)則是
So,Thumb rule while dealing with servlet is
在redirect
或forward
添加return語句之前完成你的邏輯.所以執(zhí)行到此結束.
Finish your logic before redirect
or forward
add return statement.So execution ends there .
這篇關于Servlet:提交響應后無法轉發(fā)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!