0

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?

1 Answer 1

1

When you use @BodyParser.Of(BodyParser.Json.class) you're telling play to validate the Content-Type as application/json in 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 categoryAdder since 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-Type is multipart/form-data and 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-Type is set in the jQuery ajax request.

Ref: http://www.playframework.org/documentation/2.0.4/JavaBodyParsers

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.