OGNL加法/类型强制

时间:2011-06-15 15:59:23

标签: struts2 ognl type-coercion

%{control.current + #displayRows}

最终是我需要执行的声明。我把它放在一个s:if标签中,我使用test来查看这个值是否在一定范围内。

最终,我得到字符串连接而不是添加,因为OGNL不会将添加的两侧都视为数字类型。做一点修补,我明白了

%{control.current + control.current}

会导致数字加法,所以实际上先前在s:set标记中设置的displayRows值被视为非数字值。这是我的s:set tag:

<s:set name="displayRows" value="%{#application['app_settings'].settings['MAX ACCESS FIELD TITLES ROWS']}" />

这些设置代表Java中的Map。而键总是一个字符串......好吧......值并不总是一个整数,因为存储了各种应用程序设置。因此,我们可以为值类型做的最好的事情是Object。我相信这是问题所在。 OGNL不认为这是可以自动转换为数字类型的东西。

我已经阅读了http://incubator.apache.org/ognl/language-guide.html的langauge指南,其中解释了其中的一些概念,但是我没有看到告诉OGNL的方法“是的,这个包含15的值的displayRows是一个整数”。有没有办法实现这一目标。我需要能够动态添加,所以我无法在Javaland中创建其他属性来帮助我。我查看了OGNL,s:set标签和Java级别,但我没有看到可以实现这一目标的合适位置。

1 个答案:

答案 0 :(得分:6)

Struts认为#displayRows是一个字符串,当我们需要它作为一个整数时(我假设整数你将能够将以下内容应用于任何内置类型)。

首先打开struts.xml中的静态方法访问。

这里是我的struts.xml参考,最后一个常量标记是你需要添加到你的标记:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.date.format" value="0,date,dd.MM.yyyy"/>
    <constant name="format.date" value="{0,date,dd.MM.yyyy}"/>
    <constant name="struts.ognl.allowStaticMethodAccess" value="true"/> 
</struts>

然后在你的jsp中你会做类似的事情:

<s:property value='@java.lang.Integer@valueOf("123") + @java.lang.Integer@valueOf("123")' />

显示:246

在set标签中进行转换可能会更好:

<s:set name="displayRows" value="@java.lang.Integer@valueOf(#application['app_settings'].settings['MAX ACCESS FIELD TITLES ROWS'])" />

然后,

<s:property value="control.current + #displayRows"/>

将按预期行事。

相关问题