使用Play Framework获取请求参数? [英] Get request parameter with Play Framework?

查看:359
本文介绍了使用Play Framework获取请求参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习游戏框架,并了解我可以将 / manager / user 等请求映射为:

I am learning play framework and understand that I can map a request such as /manager/user as:

  GET      /manage/:user    Controllers.Application.some(user:String)

我如何映射像 / play / video这样的请求?video_id = 1sh1

推荐答案

你至少有两种可能性,我们称之为 approach1 approach2

You have at least two possibilities, let's call them approach1 and approach2.


  1. 在第一种方法中,您可以使用某个默认值声明路径参数。 0 是一个很好的候选者,因为在它之上建立一些条件是最容易的。它也是 typesafe ,并预先验证自己。我会在开头推荐这个解决方案。

  2. 第二种方法直接从请求中读取params作为 String 所以你需要将它解析为整数并另外验证是否需要。

  1. In the first approach you can declare a routes param with some default value. 0 is good candidate, as it will be easiest to build some condition on top of it. Also it's typesafe, and pre-validates itself. I would recommend this solution at the beginning.
  2. Second approach reads params directly from request as a String so you need to parse it to integer and additionally validate if required.

routes

GET     /approach1      controllers.Application.approach1(video_id: Int ?=0)
GET     /approach2      controllers.Application.approach2

操作:

public static Result approach1(int video_id) {
    if (video_id == 0) return badRequest("Wrong video ID");
    return ok("1: Display video no. " + video_id);
}

public static Result approach2() {
    int video_id = 0;

    if (form().bindFromRequest().get("video_id") != null) {
        try {
            video_id = Integer.parseInt(form().bindFromRequest().get("video_id"));
        } catch (Exception e) {
            Logger.error("int not parsed...");
        }
    }

    if (video_id == 0) return badRequest("Wrong video ID");
    return ok("2: Display video no. " + video_id);
}

PS: LOL我刚刚意识到你想要的使用字符串标识符...无论如何两种方法都类似:)

PS: LOL I just realized that you want to use String identifier... anyway both approaches will be similar :)

这篇关于使用Play Framework获取请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆