Skip to content
Advertisement

How to return custom response on failing validation in Struts 2

Let me explain what I’m doing first :

I’m writing an API, which returns JSON on success or failure and there’s a status variable within the returned JSON, which lets the end-user know where it’s a success or failure.

Now, if an API expects to submit some parameters, then if that parameter is a double & the submitted value is a string, then I have to return JSON with status false and an error message in an errorlist.

By-default the interceptors in between, failing to set the String to some Number returns Action.INPUT result without executing the action method.

I tried annotating the method with @SkipValidation but still the method code doesn’t execute and it returns INPUT straight away from the interceptor (I guess).

I’ve by default defined the status to be true then in the action method, depending on the conditions, I set it false if required, but since now the action is never executed, the JSON response returned, is having status to be true and the errorlist is empty (since the action didn’t executed, which used to add error to the list).

Action Code:

 @SkipValidation
    public String saveFund() {
          //some code which is never executed when Double variable is a string
    return SUCCESS;
}

Interceptor stack being used:

<interceptors>
    <interceptor name="nlogin" class="interceptors.AdminInterceptor"/>
    <interceptor-stack name="loginStack">
        <interceptor-ref name="nlogin"/>
        <!--<interceptor-ref name="store">-->
        <!--<param name="operationMode">AUTOMATIC</param>-->
        <!--</interceptor-ref>-->
        <interceptor-ref name="defaultStack"/>
    </interceptor-stack>
</interceptors>
<default-interceptor-ref name="loginStack"/>

Advertisement

Answer

If the action is not executed means that you have validation errors. The validation interceptor returns Action.INPUT result in this case when the validate method complete if any.

So, you want to return a JSON in this circumstances. To return JSON you should create a result with a name "input" and type "json" and add it to the action configuration.

When the validation completed, that you might use a validate() method to customize the result, the input result will be executed and if it’s JSON type then JSON response will be returned.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement