When I used json in my controller class of Play! framework, I experienced something that I didn’t know why.
I had two ajax calls so my controller class had two corresponding method like below:
@BodyParser.Of(BodyParser.Json.class)
public static Result categoryAdder() {
....(using json)....
}
Then,
@BodyParser.Of(BodyParser.Json.class)
public static Result pathCalculator() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart = body.getFile("imageFile");
ObjectNode jsonResult = Json.newObject();
....
}
I used ajaxForm that is a plug-in for jquery to pass a file as multipartFormData.
When I put @BodyParser.Of(BodyParser.Json.class) before method pathCalculator(), this method threw an null pointer exception on FilePart filePart = body.getFile("imageFile");. This meant the request didn’t have any file inside. However, when I removed @BodyParser.Of(BodyParser.Json.class) from the method pathCalculator(), it worked well. Does @BodyParser.Of(BodyParser.Json.class) be needed? I don’t know why. The weird thing is that the method categoryAdder() works well during @BodyParser.Of(BodyParser.Json.class) is placed before.
Is there someone who knows why this situation happens?
When you use
@BodyParser.Of(BodyParser.Json.class)you’re telling play to validate theContent-Typeasapplication/jsonin your HTTP request body.If you’re passing JSON in the body of the request and use such body parser it will validate the content and throw an appropriate HTTP error if invalid. In the first case
categoryAddersince you’re using/parsing JSON inside the method it makes sense and it’s perfectly right (adds the validation).In the second case (pathCalculator) the
Content-Typeismultipart/form-dataand a JSON body parser isn’t needed as there is no JSON in the request body.Simply removing the body parser works and that’s what you should do.
Content-Typeis set in the jQuery ajax request.Ref: http://www.playframework.org/documentation/2.0.4/JavaBodyParsers