Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make action properties set from empty string parameters null

Tags:

struts2

My goal is to have an actions properties be null if they are set due to request parameters that are empty strings.

I created an interceptor that is run before the default stack, which trims all values in invocation.getInvocationContext().getParameters() to null. However, this did not fix my problem; despite the parameters now being null (verified in the action using ParameterAware), the properties are still being set to empty strings.

Upon further reading, I see that the parameters interceptor is likely the cause, in particular that:

While this interceptor is being invoked, a flag (ReflectionContextState#CREATE_NULL_OBJECTS) is turned on to ensure that any null reference is automatically created - if possible. See the type conversion documentation and the InstantiatingNullHandler javadocs for more information.

Is there some easy way to achieve my goal?

If worse comes to worse, it seems like it would be possible to extend the ParametersInterceptor class, and override the methods doIntercept(ActionInvocation invocation) and setParameters(Object action, ValueStack stack, final Map<String, Object> parameters). This just seems incredibly awkward for what, I assume, would be behaviour that many people would desire.

like image 668
Matt Avatar asked Mar 15 '26 06:03

Matt


1 Answers

I don't think too many people would really desire this behavior since it basically subverts normal HTTP parameter behavior, where unfilled parameters are an empty string.

You have a few options.

You could try to replace or extend the StrutsObjectFactory. You could try to replace or extend the InstantiatingNullHandler. Both of these are configured in struts-default.xml and should be easily overrideable.

I might take a different approach, however, since you're basically asking to work around HTTP, and annotate action fields that should be made null when their input is blank. An interceptor running after "parameters" would check the parameters against the action's properties and annotation and null them out as appropriate.

There are any number of variations on this idea, you might just have an action that has a map and "null" parameters are indicated with a map entry. This avoids annotation and method lookup (although that could be cached on class name) at the expense of some additional code.

like image 119
Dave Newton Avatar answered Mar 17 '26 03:03

Dave Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!