2

Struts 2, 2.3.20 mentioned that

Support for accessing static methods from expression will be disabled soon, please consider re-factoring your application to avoid further problems!

We have used OGNL static calls in validators:

@ExpressionValidator(
 expression = "@foo.bar@isValidAmount(amount)",
 key = "validate.amount.is.not.valid"),

Also we used it in tags

<s:set var="test"
value="@foo.bar@sampleMethod(#attr.sampleObject.property1)" />

Well, what is the best way to refactor above two usages ?!

Roman C
  • 49,761
  • 33
  • 66
  • 176
Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173
  • 3
    by adding wrapping such methods in action? – Lukasz Lenart Jan 19 '15 at 09:03
  • This is the wrong approach in the first place; if this is application-wide functionality you should have custom validators, which likely already exist as business logic and just need to be wrapped up as validators. – Dave Newton Jan 20 '15 at 00:37
  • @DaveNewton, thanks for comment. we use custom validators a lot and they are life saver :) But we can not use them in expression valitors. Can you please review my question at and comment it: http://stackoverflow.com/questions/28038827/struts-2-reusing-custom-expresion-validator – Alireza Fattahi Jan 20 '15 at 06:14

1 Answers1

3

In your code you are using a static method call. The best way is to create a method in the action class that wraps a static methods and use it in OGNL.

public class Wrapper {
  public boolean isValidAmount(amount){
     return foo.barr.isValidAmount(amount);
  }
  public Object sampleMethod(Object property1){
     return foo.barr.sampleMethod(Object property1);
  }

}

As soon as action bean is in the value stack you can use

@ExpressionValidator(
 expression = "isValidAmount(amount)",
 key = "validate.amount.is.not.valid"),

or in JSP

<s:set var="test"
value="sampleMethod(#attr.sampleObject.property1)" />
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • I got the idea. Do you think it is a good idea to add a method to `ActionSupport` which calls static methods, so we can use `callStaticMethod('foo.bar.validAamount','amount')` The `callStaticMethod`can use reflection or OGNL to call the method. In this way the codes which already use OGNL Static call will remain unchanged. – Alireza Fattahi Jan 19 '15 at 12:15
  • 1
    Using strings and reflection in the code is difficult to maintain and refactor. Also the code that is using reflection extensively slows down performance. At least it was years before, actually the new JVM is highly optimized but the code itself is hardcoded and lacks of usability. – Roman C Jan 19 '15 at 12:29