Tuesday 3 December 2013

Spring Mvc : Exception: String can't be cast to object while submitting from jsp Illegel argument Exception .

You can use the concept of property editor .In this we can create our custom property editors.
Sometimes what happen when submitting action in jsp . We are using reference of another entities in our model attribute. At that time controller method is expecting object and jsp is providing string.So in that case we can use property editors.


public class ABCPropertyEditor extends PropertyEditorSupport {

    private AbcService abcService;

    public ABCPropertyEditor(AbcService abcService) {
        this.abcService= abcService;
    }

    @Override
    public void setAsText(String s) {            //getting id of embeded entity
        Abc abc = abcService.getAbc(s);     //get object from id using any ORM tool
        this.setValue(abc);                            //returning object
    }
}





In controller with the help of @InitBinder we can use this property editor which get called automatically as request comes from jsp:

@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Abc.class, new ABCPropertyEditor (abcService));
}

No comments:

Post a Comment