簡體   English   中英

Servlet 到 JSP 總是傳遞空值

[英]Servlet to JSP always passing null value

我剛開始使用 JSP 和 Servlet,所以遇到了一個非常基本的問題。 我正在嘗試從 JSP 向 servlet 發出請求,在那里我設置了一個參數,然后將來自 servlet 的答案轉發回 jsp。 這是我的 JSP 中的代碼:

<% String s = (String)request.getAttribute("name");
   out.println(s);
%>

這是我的 servlet 代碼:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    try (PrintWriter out = response.getWriter()) {
        request.setAttribute("name", new String("aa"));
        this.getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
    }
}

所以最后,servlet 有價值,但我的 jsp 沒有。

在沒有作者的情況下嘗試,您不希望對單個響應有兩個寫作上下文。 你也沒有使用它:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setAttribute("name", new String("aa"));
    this.getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}

這里你已經聲明了一個 String 類型,但你也將它轉換為 String ,這是多余的。

<% String s = (String)request.getAttribute("name");
   out.println(s);
%>

此外, <%= %><% %>之間存在差異。 如果要將變量輸出到 jsp 中,請使用帶有等號 ( <%= %> ) 的變量。 scriptlet 代碼的第二行也會產生錯誤。 您在 servlet 中編寫的代碼不僅會在 JSP 上繼續運行,而且不是如何工作的。

如果要輸出 name 屬性,請執行以下操作:

<%= request.getAttribute("name") %>

然而,自 2010 年以來不鼓勵使用 scriptlet(過時的技術)。我們改用 EL 和 JSTL。 您應該能夠像這樣輸出變量:

${name}

在您的 Servlet 中,您需要做的就是:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  String name = "Jane"; //create a string
  request.setAttribute("name", name); //set it to the request

  RequestDispatcher rs = request.getRequestDispatcher("index.jsp"); //the page you want to send your value
  rs.forward(request,response); //forward it

}

編輯

你問,

有沒有辦法觸發 servlet 讓我們說單擊按鈕或類似的東西?

是的,有多種方法可以做到這一點,這實際上取決於您希望如何設置。 在單擊按鈕時觸發 servlet 的簡單方法是這樣的。 *(假設您有一個 servlet 映射到/Testing ):

<a href="/Testing">Trigger Servlet<a>

另一種方法可能是使用表格:

<form action="Testing" method="get">
<input type="hidden" name="someParameterName" value="you can send values like this">
<button type="submit">Do some magic</button>
</form>

還有 AJAX(涉及 javascript)。 但這是相當先進的,在您熟悉正常的同步http 行為之前,我不建議您這樣做。

我認為您應該使用請求對象調用請求調度程序方法。 這是你如何做到的:

RequestDispatcher rs = request.getRequestDispatcher("index.jsp");
rs.forward(request,response);

暫無
暫無

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

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