Reputation: 3609
I have a Spring 3 MVC Controller who has a @ModelAttribute parameter of an object
This object contains numerous properties, mostly strings/numbers. It has one java.sql.Timestamp property.
I call this method via browser, passing the properties as separate query string key/value pairs. When I do not pass a key/value pair for the Timestamp everything works fine, it loads the object with all my properties.
But as soon as I try to send a value for the Timestamp proeprty, I get an immediate Error 400: Bad request.
I know i have to send the data string in a specific format, but I just use a JsonDeserializer so that I can parse the string using the format that I want. But when I set a breakpoint inside my JsonDeserializer, it never gets hit. Spring seems to just ignore it. What did I miss?
Some code:
Controller:
@RequestMapping(headers = "Accept=application/json;charset=utf-8", value = "/doSomething", method = RequestMethod.GET)
@ResponseBody
public ReturnObject doSomething(@ModelAttribute MyObject obj, HttpServletRequest request) throws Exception {
//blah blah
}
MyObject:
public class MyObject {
private Integer someNumber;
private String someString;
@JsonDeserialize(using=ShortDateDeserializer.class)
private Timestamp someTimestamp;
// getter/setters like usual....
}
ShortDateDeserializer:
public class ShortDateDeserializer extends JsonDeserializer<Timestamp> {
Logger logger = Logger.getLogger(ShortDateDeserializer.class);
@Override
public Timestamp deserialize(JsonParser parser, DeserializationContext ctx) throws IOException, JsonProcessingException {
try {
String rawDate = parser.getText();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
return new Timestamp(sdf.parse(rawDate).getTime());
} catch (Exception e) {
logger.error("Failed to parse date: "+parser.getText());
throw new IOException("Failed to parse date: "+parser.getText());
}
}
}
When I call my service only setting the number/string like so:
localhost/doSomething?someNumber=1&someString=xyz
Works fine.
When I also attempt to set a value for the timstamp:
localhost/doSomething?someNumber=1&someString=xyz&someTimestamp=09/15/2013
I get an immediate Error 400: bad request.
What did I miss in order to get spring to use my custom timestamp parsing code when populating MyObject?
Upvotes: 0
Views: 2189