简体   繁体   中英

play 2.3.x framework: How to decline all non application/json requests

In play 2.3, how can I automatically reject (return BadRequest) all incoming requests that are not of type application/json? Is there an annotation type like for BodyParsers?

I don't want to add an extra check:

@BodyParser.Of(BodyParser.Json.class)
public static Result sendMessage() {
    JsonNode requestBody = request().body().asJson();
    if (requestBody == null) {
        return badRequest("Bad Request: Not JSON request");
    }
return ok();
}

Probably the most flexible way is creating own interceptor - aka Action composition

Sample RequiredJson.java (let's place it in new annotations package)

package annotations;

import com.fasterxml.jackson.databind.JsonNode;
import play.libs.F;
import play.mvc.Http;
import play.mvc.Result;

public class RequiredJson extends play.mvc.Action.Simple {
    @Override
    public F.Promise<Result> call(Http.Context ctx) throws Throwable {

        boolean hasCorrectType = ctx.request().getHeader("Content-Type") != null && ctx.request().getHeader("Content-Type").equals("application/json");
        JsonNode json = ctx.request().body().asJson();

        if (!hasCorrectType || json == null) {
            return F.Promise.<Result>pure(badRequest("I want JSON!"));
        }
        return delegate.call(ctx);
    }
}

So you can use this annotation for whole controller(s) or for selected action(s) only like:

@With(annotations.RequiredJson.class)

Result: if Content-Type isn't valid or if incoming data isn't valid JSON it returns badRequest, otherwise it calls the requested action as usually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM