2012-08-27 39 views
0

可能重複:
How to pass an Object from the servlet to the calling JSP如何將對象從servlet傳遞到JSP?

如何傳遞對象由servlet來JSP?

我已經使用在servlet側

request.setAttribute("ID", "MyID"); 
request.setAttribute("Name", "MyName"); 
RequestDispatcher dispatcher = request.getRequestDispatcher("MangeNotifications.jsp"); 
if (dispatcher != null){ 
dispatcher.forward(request, response); 
} 

以下代碼,該代碼在JSP側

<td><%out.println(request.getAttribute("ID"));%> </td> 
    <td><%out.println(request.getAttribute("Name"));%> </td> 

我得到的JSP頁面

+1

你嘗試了什麼?你在哪裏失敗?你期待什麼?你得到了什麼? – npinti

+0

dup:http://stackoverflow.com/questions/12033092/how-to-pass-an-object-from-the-servlet-to-the-calling-jsp –

+0

http://stackoverflow.com/questions/12033092/how-to-pass-an-object-from-the-servlet-to-the-calling-jsp/12033175#12033175 –

回答

1

我認爲servlet的服務(doGet/doPost)方法沒有被請求。爲了在JSP中訪問請求屬性,您的必須通過url-pattern請求servlet,這樣您就不必使用會話。

SampleServlet.java


@WebServlet(name = "SampleServlet", urlPatterns = {"/sample"}) 
public class SampleServlet extends HttpServlet { 

@Override 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    request.setAttribute("ID", "MyID"); 
    request.setAttribute("Name", "MyName"); 
    RequestDispatcher dispatcher = request 
         .getRequestDispatcher("/MangeNotifications.jsp"); 
    if (dispatcher != null){ 
     dispatcher.forward(request, response); 
    } 
    } 
} 

MangeNotifications.jsp(我假定這個文件位於網絡的上下文根)


<br/>ID : ${ID}  Or scriptlets <%-- <%=request.getAttribute("ID")%> --%> 
<br/>ID : ${Name} 

現在,打開瀏覽器,設置請求網址設置爲這樣,

http://localhost:8084/your_context/sample 
+0

我得到一個空字段 ID: ID: – user1576197

+0

如果您請求'MangeNotifications.jsp'那麼它將是空的,如果你通過servlet-url請求,那麼它*必須*不能爲空。 – adatapost

+0

即使我使用servlet URL,仍然爲空 – user1576197

1

空結果把它放在會話(session.setAttribute("foo", bar);)或請求中;那麼它可以通過你給它的名稱(在我的例子中是「foo」)從JSP訪問。

編輯: 只需使用<%= ID %><%= Name %>而不是<%out.println.....%>。注意java標記開頭的=,指示輸出表達式的結果。

+0

我得到空結果 – user1576197

+0

您訪問它錯誤的方式,我編輯了我的答案。 – kgautron

+0

org.apache.jasper.JasperException:無法編譯JSP的類: jsp文件中的行:27處出現錯誤:/ MangeNotifications。JSP ID不能被解析爲一個變量 24: 25: 26: 27:​​<%=ID%> 28: 29:​​ 30:​​  – user1576197