【问题标题】:Struts 2 using StringUtils in validator expersionsStruts 2 在验证器实验中使用 StringUtils
【发布时间】:2016-10-05 09:27:19
【问题描述】:

我们正在使用 Struts 2 验证器 @FieldExpressionValidator@ExpressionValidator。这些验证器检查 OGNL 表达式。我们在这些表达式中处理字符串的情况很多。

expression="(captcha=='' && captcha== null || ....)

我们发现如果我们可以在这里使用 StringUtils ( isEmpty ,trimToEmpty,... ) 是非常有用的。

当我们将 struts.ognl.allowStaticMethodAccess 设置为 false 时,出于安全问题,我们尝试通过将此 getter 添加到操作中来解决它

public StringUtils getStringUtils(){
        return new StringUtils();
    }

然后在表达式中stringUtils.isEmpty(captcha)。但它没有用。

为了调试我们测试了

ActionContext.getContext().getValueStack().findValue("stringUtils"); //returns org.apache.commons.lang3.StringUtils@693ade51 which shows there is an object in the stack

ActionContext.getContext().getValueStack().findValue("stringUtils.isEmpty('dd')"); //returns null

任何cmets?!

【问题讨论】:

    标签: java struts2 ognl valuestack


    【解决方案1】:

    isEmpty 是一个静态方法,应该使用类前缀静态访问。一旦您使用 OGNL,您就必须允许静态方法访问或为该方法编写一个包装器,即

    public boolean stringUtilsIsEmpty(String captcha) {
        return StringUtils.isEmpty(captcha);
    }
    

    然后

    ActionContext.getContext().getValueStack().findValue("stringUtilsIsEmpty('dd')");
    

    但是,在 JSP 中你可以这样做

    <s:if test="captcha != null && captcha != ''">
      do something
    </s:if>
    

    这和StringUtils#isEmpty()一样。

    【讨论】:

    • 所以我应该为StringUtils 的每个方法添加一个方法:-( 有更好的解决方案吗?
    • 可能有很多方法可以做到这一点。我不知道您具体要问什么,有效的代码在这里,在您的问题中无效的代码。澄清你的具体问题,否则它看起来太宽泛了。或者您只是在寻找 cmets?
    • 亲爱的@RomanC 是的,代码有效,谢谢,我正在寻找一种enhancement 的方法,它不需要为每个StringUtils 方法定义单独的每个方法。如果您认为这是另一个问题,我可以用不同的方式提出!
    • 如果你明确了你的实际需要,你可能会问另一个问题。
    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多