【问题标题】:Is it possible to define a variable in Java and use that in JSP code?是否可以在 Java 中定义一个变量并在 JSP 代码中使用它?
【发布时间】:2014-09-03 10:29:42
【问题描述】:

我有一个如下所示的下拉菜单:

<html:select styleId="colorCodeId" property="msSpec.colorcodeId" name="Form"  styleClass="form-control">
                            <option value="-1"></option>
                            <html:optionsCollection property="colorcodeList" style="background: <%=test1%>;"/>
                        </html:select>

在 Java 代码中我有:

List<LabelValueBean> colorcodeList = new ArrayList<LabelValueBean>();
for (Mty property : customPropertyList) {
            LabelValueBean bean = new LabelValueBean(property.getName(), property.getId().toString());

if (property instanceof ColorCode) {
                test1 = property.getName();
                System.out.println("test1: " + test1);
                colorcodeList.add(bean);
            }
}

我是否可以像上面一样定义test1 并将其用作下拉菜单中的背景颜色?现在不行。

【问题讨论】:

    标签: java jsp jstl struts el


    【解决方案1】:

    您可以使用 JSP EL 表达式代替变量。原因是从代码中删除 scriptlet。

    <html:select styleId="colorCodeId" property="msSpec.colorcodeId" name="Form"  styleClass="form-control" style="${test1}">
                                <option value="-1"></option>
                                <html:optionsCollection property="colorcodeList" />
                            </html:select> 
    

    在你写的动作中

    List<LabelValueBean> colorcodeList = new ArrayList<LabelValueBean>();
    for (Mty property : customPropertyList) {
                LabelValueBean bean = new LabelValueBean(property.getName(), property.getId().toString());
    
    if (property instanceof ColorCode) {
                    test1 = property.getName();
                    System.out.println("test1: " + test1);
                    request.setAttribute("test1", "background: "+test1+";");
                    colorcodeList.add(bean);
                }
    
    }
    

    【讨论】:

    • 当我将请求放入我的 java 代码时,它说请求无法解析。我应该导入一个库吗?
    • 它可供您操作。
    【解决方案2】:

    JSP 表达式语言不能使用在自定义 Java 代码中声明的 Java 变量。

    JSP 表达式语言可以访问的“变量”实际上是设置在 JSP/Servlet 框架定义的四个“范围”之一中的属性;即“会话”、“请求”、“页面”和“应用程序”。

    您可以从 Java 中获取和设置这些属性;例如

       // Request scope
       request.getAttribute("test1");  
       request.setAttribute("test1", someValue);
    

    更多信息:


    当我将请求放入我的 java 代码时,它说请求无法解析。我应该导入一个库吗?

    如果您的代码嵌入在 JSP 中,则应声明 request

    否则,请将request 替换为引用当前请求的HttpServletRequest 对象的变量的名称。

    【讨论】:

      猜你喜欢
      • 2017-12-02
      • 2015-06-19
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多