I'm testing out the @InitBinder
annotation so I can have String
objects converted into appropriate Enum
objects during web requests.
I created the following simple Enum
:
SampleEnum.java
public enum SampleEnum {
ONE,
TWO,
THREE,
FOUR,
FIVE;
}
Then, I created an editor extending PropertyEditorSupport
to be called from the @InitBinder
code:
EnumPropertyEditor.java
@SuppressWarnings("rawtypes")
public class EnumPropertyEditor extends PropertyEditorSupport {
private Class clazz;
public EnumPropertyEditor(Class clazz) {
this.clazz = clazz;
}
@Override
public String getAsText() {
return (getValue() == null ? "" : ((Enum) getValue()).name());
}
@SuppressWarnings("unchecked")
@Override
public void setAsText(String text) {
Enum e = Enum.valueOf(clazz, text);
setValue(e);
}
}
Then, in my controller I added the @InitBinder
and a simple request mapping:
Controller
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(SampleEnum.class, new EnumPropertyEditor(SampleEnum.class));
}
@RequestMapping(method = POST, value = "/postSampleEnum")
@ResponseBody
public SampleEnum postSampleEnum(@RequestBody SampleEnum sampleEnum) {
return sampleEnum;
}
From my understanding, a request for this controller method should attempt to convert a string value into the SampleEnum
object. However, no breakpoints are hit in either initBinder
, request mapping method, nor any of the methods in the EnumPropertyEditor
.
I'm testing with RESTClient in FireFox, and have tried sending in the request body "THREE", which I would expect to work. Instead, I get a 415 error regardless of the what's in the request body. (The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().)
If I change the request mapping to take in a string instead of a SampleEnum
, the postSampleEnum
gets called and doesn't use the custom editor (as expected).
Am I missing anything that allows the custom editor code to be called? What is the best way to continue debugging this?
First of all, I forgot to add the application/json content-type to the request header in RESTClient. >_<
However, I noticed that the code execution still doesn't go through the custom property editor. As GriffeyDog said, it looks like the code only executes if I switch to a RequestParam
or ModelAttribute
.