簡體   English   中英

EL需要request.setAttribute(“...”)嗎?

[英]Is request.setAttribute(“…”) necessary with EL?

如果我有一個包含以下代碼的bean:

private String method;

public String getMethod() {
    return method;
}

public void setMethod(String method) {
    this.method = method;
}

是否有必要:

request.setAttribute("method", method );

對於我希望從JSP中看到的每個變量?

如果未在請求中設置method屬性,則在jsp中,已計算的${method}表達式將為null。 如果您需要某個值,則必須將其設置為該值。

在你的servlert做post方法;

public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException 
{       
 String formParameter = req.getParameter("someParameterName");
 //Your logic dependen on form parameter

 FormObject fo = new FormObject();
 fo.setMethod("new value"); 
 req.setAttribute("formObject", fo);
 req.getRequestDispatcher("/WEB-INF/yourJspPage.jsp").forward(req, res);
}

你的java對象:

public class FormObject{
      String method;

      public String getMethod(){
         return method;
      }

      public void setMethod(String method){
         return this.method = method;
      }
    }

在yourJspPage.jsp中:

<div>${fo.method}</div>

PS我沒試過這個例子,但這個想法應該是清楚的。 你可以搜索jsp + servlet教程來了解你在做什么。 你想要的類似: 在這里輸入鏈接描述

session類似於請求只是添加到此對象的屬性持續更長時間(不同的范圍)。 但我認為在為每個步驟尋求幫助之前,您應該閱讀更多文檔和教程。

對於我希望從JSP中看到的每個變量?

不需要。您只需將bean的實例設置為請求屬性即可。 使用JSP頁面中提供的那個,您可以使用EL - ${beanInstance.method}訪問該bean的屬性。

如果未在請求中設置method屬性,則在jsp中,已計算的${method}表達式將為null。 如果您需要某個值,則必須將其設置為該值。


3種方法可以做到這一點:

  1. 隨着一個會話

    request.getSession().setAttribute("method", this); <c:out value="${mycontroller.method}"/>

  2. 設置單個屬性

    request.setAttribute("method", method); <c:out value="${method}"/>

  3. 通過將對象分配給bean,同時設置bean中的所有屬性

    request.setAttribute("mycontroller", this); <c:out value="${mycontroller.method}"/>

暫無
暫無

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

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