Enrique San Martín Enrique San Martín - 6 months ago 11
Java Question

How to validate input from form in struts2 action

I have a jsp with a struts2 form that has a input widget of type number, if I empty this widget and then submit to the form, in struts (before my validation method) I get this in the debug logging:

19:10:30,734 ERROR [com.opensymphony.xwork2.interceptor.ParametersInterceptor.error:34] Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'someDto.intCol' on 'class mypackage.MyAction: Error setting expression 'someDto.intCol' with value ['', ]


I would like to capture this exception (the "Unexpected Exception") do something and then in the validator (in the action) setup the errors with addFieldError from the ActionSupport class,

Thanks for the help :)

EDIT:

The dto class:

public class SomeDto() {

private Integer intCol; //{with getters&setters}


The problem is that when the user clear the input in the Form (in the jsp), struts try to convert [''] (or String empty in others words) to an Integer with the ParametersInterceptor class (like in the log line up).

So, the dto has the getters and setters.

Answer

You can use the "ParameterAware" interceptor:

@Override
public void setParameters(Map<String, String[]> parameters) {
    log.info("parameters: " + parameters);

    if (parameters.get(someDto.intCol")[0].length() == 0) {
        parameters.put("someDto.intCol", new String[]{"0"});
    }
}

This will catch the param from the jsp and if if empty will put 0 instead,

Regards.