繁体   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