Converting from String to custom Object for Spring MVC form Data binding?

Just as a supplement to Mark’s answer, here is what I ended up doing in my controller.

@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    binder.registerCustomEditor(Server.class, "serverId", new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            Server type = (Server) em.createNamedQuery("Server.findById")
                .setParameter("id", Short.parseShort(text)).getSingleResult();
            setValue(type);
        }
    });
}

You can also do this using Spring injection, as opposed to anonymous classes. This outlined by the link in Mark’s answer.

You you may also be able to extend ClassEditor (see below) instead of PropertyEditorSupport. The Javadoc states;

Property editor for java.lang.Class, to enable the direct population of a Class property without recourse to having to use a String class name property as bridge.

Don’t know if I fully understand the benefit of this, but something to keep in mind.

Useful Javadocs

Leave a Comment