簡體   English   中英

如何從servlet到jsp獲得響應?

[英]How to get response from servlet to jsp?

我正在嘗試從servlet使用獲得響應

request.setAttribute(error, error);
request.getRequestDispatcher("http://localhost:8080/redicted_test/Home.jsp").forward(request, response);

String redictedURL="http://localhost:8080/redicted_test/Home.jsp";
response.sendRedirect(redictedURL);

但得到錯誤

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

我明白我發送了兩次響應,但我怎么能做到呢? 你能告訴我最簡單的方法嗎?

您已經轉發了請求,現在您正在重定向它

request.getRequestDispatcher("http://localhost:8080/redicted_test/Home.jsp").forward(request, response);
..
response.sendRedirect(redictedURL);

如果你想從servlet設置一些屬性並需要在jsp上顯示它,那么只需將請求轉發給jsp並顯示這些屬性

在您的示例中,您已執行了jsp,並且已在回復緩沖區中發送了呈現的jsp。 由於您已開始發送響應,因此發送了響應標頭。 但就在此之后,您想要發送重定向,重定向是一種標頭操作(更改http狀態代碼和位置標頭)。

我想你應該使用include而不是forward ..

forward is used to forward a request, that is control is transfered to the
new servler/jsp. u shud take care to not put any our.println() statements 
in the servlet from where u plan to call forward method. in fact u cant even 
fire response.getWriter() method in this case. u can only do that in the servlet
to which the control is bein fwded 

如果要將請求轉發給另一個servlet或JSP,切勿將任何內容寫入響應。 例如,如果Servlet1將請求轉發給Servlet2,Servlet1不應該將任何內容寫入響應,也不應該調用response.getOutputStream()方法。這是不允許的,無論servlet1寫入響應的是什么都不會輸出,否則您將獲得IllegalStateException 。

include - means that the new servlet/jsp will be procesed and any
out.println()/html stuff will be included and then control will come
back to the servlet/jsp that called include method. 

RequestDispatcher.forward() ,響應將被提交並關閉。 您無法在響應中寫入任何標頭/內容。

這就是為什么在執行RequestDispatcher.forward()之后,您無法redirectdo operation which adds header or response content

你有的替代方案是使用include而不是forward。

但是,我不明白你的用例。 您正在轉發並重定向到同一頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM