如何在AWS Lambda POJO处理程序中使用路径参数

时间:2018-04-13 20:22:15

标签: java json amazon-web-services aws-lambda pojo

我正在尝试在我的POJO处理程序中同时使用http主体和路径参数。当我目前没有事件对象时,如何访问路径参数?

我的处理程序看起来像这样:

@Override
public Object handleRequest(MyCustomModel model, Context context) {
  // Doing stuff with model that was deserialized in request body
  // but need path param '/some/path/{id}'
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,您最好自己处理事件对象。为此,使用lambda的lambda代理集成配置API网关,然后根据事件主体和路径参数的内容自行填充自定义模型对象。

这是一个excerpt from an example in the AWS documentation,展示了如何阅读事件对象:

    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

    LambdaLogger logger = context.getLogger();
    logger.log("Loading Java Lambda handler of ProxyWithStream");


    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    JSONObject responseJson = new JSONObject();
    String name = "you";
    String city = "World";
    String time = "day";
    String day = null;
    String responseCode = "200";

    try {
        JSONObject event = (JSONObject)parser.parse(reader);
        if (event.get("queryStringParameters") != null) {
            JSONObject qps = (JSONObject)event.get("queryStringParameters");
            if ( qps.get("name") != null) {
                name = (String)qps.get("name");
            }
        }

        if (event.get("pathParameters") != null) {
            JSONObject pps = (JSONObject)event.get("pathParameters");
            if ( pps.get("proxy") != null) {
                city = (String)pps.get("proxy");
            }
        }

        if (event.get("headers") != null) {
            JSONObject hps = (JSONObject)event.get("headers");
            if ( hps.get("day") != null) {
                day = (String)hps.get("day");
            }
        }

        if (event.get("body") != null) {
            JSONObject body = (JSONObject)parser.parse((String)event.get("body"));
            if ( body.get("time") != null) {
                time = (String)body.get("time");
            }
        }
...