How to bind request body to action method parameter?
I understand how Play binds URI segments or parameters to action method parameters. I also saw how an uploaded file can be accessed.
But I am still looking for the way to bind the request entity of a PUT or POST request to a method parameter.
Suppose the request is sth like
PUT /blog/entries/67
Content-Type: application/atom+xml
<entry>...</entry>
And I would like to bind that to an entry parameter:
public static void (String entryId, Entry entry) {
// entryId开发者_JAVA技巧 being 67
// entry being the deserialized Atom payload (e.g. using Apache Abdera parser)
backend.updateEntry(67,entry);
// AtomPub's 'canonical' response is the updated entry.
render(entry)
}
Two questions:
Does something like this work?
Where do I find the documentation of how to create the deserializer?
Take a look at the Custom Binding documentation on the Play site.
http://www.playframework.org/documentation/1.2.3/controllers#custombinding
I think what you are looking for is play.data.binding.TypeBinder
, which allows you to customise the way Play binds certain objects in your controller.
Update:
Looking at the play groups, Guillaume has posted the following code for handling JSON in the body of a POST, so this could easily be adapted to get XML from an atom+xml input. It uses a BinderPlugin, rather than the TypeBinder, which allows you to do more pwerful binding operations.
package plugins;
import play.*;
import play.mvc.*;
import com.google.gson.*;
import java.util.*;
import java.lang.reflect.*;
import java.lang.annotation.*;
public class BinderPlugin extends PlayPlugin {
public Object bind(String name, Class clazz, Type type, Annotation[] annotations, Map<String, String[]> params) {
if(Http.Request.current().contentType.equals("application/json")) {
JsonObject json = new JsonParser().parse(Scope.Params.current().get("body")).getAsJsonObject();
if(clazz.equals(String.class)) {
return json.getAsJsonPrimitive(name).getAsString();
}
}
return null;
}
}
精彩评论