Asa
Asa

Reputation: 1729

Struts2 raising type conversion errors for specific types only

We have a custom type converter registered in our app, lets say FooTypeConverter, which is responsible for converting to and from type Foo. We are not interested in type conversion errors of other types, but we would want to raise a validation error if a type conversion of a target type Foo fails. We are interested in both String=>Foo and Foo=>String

I know this can be achieved with a ConversionErrorFieldValidator, but this means decorating the target fields. Is there any way that we can achieve this with some global setup?

Thanks and best regards, Asa

Upvotes: 0

Views: 568

Answers (1)

Dave Newton
Dave Newton

Reputation: 160181

Nutshell: Replace the default "conversionError" interceptor and replace it with a version that overrides shouldAddError that returns true iff the value's type is Foo.

Details: The default interceptor is an extension of XWork's ConversionErrorInterceptor that mostly checks values. It also checks for a specific type, so I think this is the cleanest hook. Override shouldAddError and return true iff the value type is the one you're interested in.

Roughly:

protected boolean shouldAddError(String propertyName, Object value) {
    return value instanceOf Foo;
}

You may wish to retain some of the value checks, so double-check. It might be easiest to call super.shouldAddError first, and do your check iff it returns true.

Upvotes: 2

Related Questions