tags:

views:

2195

answers:

4

I need to pass a UUID instance via http request parameter. Spring needs a custom type converter (from String) to be registered. How do I register one?

A: 

Not sure what you are asking?

Spring comes with a CustomEditorConfigurer to supply custom String <-> Object converters.

To use this, just add the CustomEditorConfigurer as bean to your config, and add the custom converters. However, these converters are typically used when converting string attributes in the config file into real objects.

If you are using Spring MVC, then take a look at the section on annotated MVC

Specifically, have a look at the @RequestParam and the @ModelAttribute annotations?

Hope this helps?

toolkit
+3  A: 

Please see chapter 5 of the spring reference manual here: 5.4.2.1. Registering additional custom PropertyEditors

MetroidFan2002
+4  A: 

I have an MVC controller with RequestMapping annotations. One method has a parameter of type UUID. Thanks toolkit, after reading about WebDataBinder, I figured that I need a method like this in my controller:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(UUID.class, new UUIDEditor());
}

UUIDEditor simply extends PropertyEditorSupport and overrides getAsText() and setAsText().

Worked for me nicely.

alexei.vidmich
A: 

In extenstion to the previous example.

Controller class

@Controller
@RequestMapping("/showuuid.html")
public class ShowUUIDController
{

  @InitBinder
  public void initBinder(WebDataBinder binder)
  {
    binder.registerCustomEditor(UUID.class, new UUIDEditor());
  }

  public String showuuidHandler (@RequestParam("id") UUID id, Model model)
  {
    model.addAttribute ("id", id) ;
    return "showuuid" ;
  }
}

Property de-munger

class UUIDEditor extends java.beans.PropertyEditorSupport
{

  @Override
  public String getAsText ()
  {
    UUID u = (UUID) getValue () ;
    return u.toString () ;
  }

  @Override
  public void setAsText (String s)
  {
    setValue (UUID.fromString (s)) ;
  }

}
David Newcomb