Struts 2 using StringUtils in validator expersions

2019-05-29 20:31发布

We are using Struts 2 validators @FieldExpressionValidator and @ExpressionValidator. These validators check on OGNL expression. There are lots of cases where we deal with Strings in these expressions.

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

We find it is very useful if we can use StringUtils ( isEmpty ,trimToEmpty,... ) here.

As we set the struts.ognl.allowStaticMethodAccess to false, for security issues, we tried to solve it by adding this getter to action

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

and then stringUtils.isEmpty(captcha) in the expression. But it didn't work.

To debug we tested

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

Any comments ?!

1条回答
趁早两清
2楼-- · 2019-05-29 20:31

isEmpty is a static method and should be accessed statically with class prefix. As soon as you are using OGNL you have to allow static method access or write a wrapper for the method, i.e.

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

then

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

However, in JSP you can do

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

This is doing the same likeStringUtils#isEmpty().

查看更多
登录 后发表回答