3

Having my ValueObject

UserVO {
  long id;
  String username;
}

I created custom editor for parsing this object from string id#username

public class UserVOEditor extends PropertyEditorSupport {

@Override
public void setAsText(String text) throws IllegalArgumentException {
    Preconditions.checkArgument(text != null,"Null argument supplied when parsing UserVO");
    String[] txtArray = text.split("\\#");
    Preconditions.checkArgument(txtArray.length == 2, "Error parsing UserVO. Expected: id#username");
    long parsedId = Long.valueOf(txtArray[0]);
    String username = txtArray[1];
    UserVO uvo = new UserVO();
    uvo.setUsername(username);
    uvo.setId(parsedId);
    this.setValue(uvo);
}

@Override
public String getAsText() {
    UserVO uvo = (UserVO) getValue();
    return uvo.getId()+'#'+uvo.getUsername();
}

in my controller i register

@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
    binder.registerCustomEditor(UserVO.class, new UserVOEditor());
}

having in my model object ModelVO

ModelVO { 
           Set<UserVO> users = new HashSet<UserVO>();
}

after custom editor is invoked all you can see after form submission is

ModelVO {
          Set<String> users (linkedHashSet)
}

so when trying to iterate

for(UserVO uvo : myModel.getUser()){ .. }

Im having classCastException .. cannot cast 1234#username (String) to UserVO .. HOW THIS MAGIC IS POSSIBLE ?

Ralph
  • 118,862
  • 56
  • 287
  • 383
Jan
  • 138
  • 1
  • 8

1 Answers1

0

It is not magic, it is because of Generics will be only proved at compile time. So you can put every thing in a Set at runtime, no one will check if you put the correct type in the Set.

What you can try, to make spring a bit more clever, is to put the ModelVO in your command object.

<form:form action="whatEver" method="GET" modelAttribute="modelVO">


@RequestMapping(method = RequestMethod.GET)
public ModelAndView whatEver(@Valid ModelVO modelVO){
   ...
}
Ralph
  • 118,862
  • 56
  • 287
  • 383
  • @Jan: BTW Spring 3.0 has the concept of org.springframework.core.convert.converter.Converter. It is like a one way property editor, but it is stateless and because of this much more performant. – Ralph Apr 05 '11 at 15:02
  • 2
    Its there ;-) Ok. So now I figured out that the proper way to register custom editors for collections is binder.registerCustomEditor(Set.class, "recipients", new CustomCollectionEditor(...){ .. } ); with implemented convertElement. So I did that. While debugging convertElement is run, however after form submission list is still not being populated (contains 0 elements :) – Jan Apr 05 '11 at 15:25
  • @Jan: >While debugging convertElement is run, however after form submission list is still not being populated -- Post a new question, which contains your JSP and Controller – Ralph Apr 05 '11 at 15:48