OGNL加法/类型强制

dem*_*lem 3 struts2 ognl type-coercion

%{control.current + #displayRows}
Run Code Online (Sandbox Code Playgroud)

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

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

%{control.current + control.current}
Run Code Online (Sandbox Code Playgroud)

确实导致数字加法,所以实际上先前在s:set标签中设置的displayRows值被认为是非数字值.这是我的s:set标签:

<s:set name="displayRows" value="%{#application['app_settings'].settings['MAX ACCESS FIELD TITLES ROWS']}" />
Run Code Online (Sandbox Code Playgroud)

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

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

Qua*_*ion 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>
Run Code Online (Sandbox Code Playgroud)

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

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

显示:246

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

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

然后,

<s:property value="control.current + #displayRows"/>
Run Code Online (Sandbox Code Playgroud)

将按预期行事.

  • 最后一个关于这个问题的最后一个想法...有趣的是,+如果你自动将其视为连接,因为如果你执行类似%{control.current - - (control.current)}的操作,它将被视为加法.我并不是说这是一种很好的做法,但这可能是解决问题的一种方法. (2认同)