将动态值传递给路由URI

时间:2013-02-02 13:04:07

标签: java playframework playframework-1.x

我正在尝试根据文本框的内容向Routes URI路径发送动态值,但是当我尝试时,它将变为null。

这就是我的尝试:

<form action="@{Application.hello(myName)}" method="get">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>

我希望在文本框中输入的值传递给路径文件,但它不起作用。如果我传递一个常量字符串,如:

<form action="@{Application.hello('John')}" method="get">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>

然后我的代码工作正常,但我不想要一个恒定的值;我希望文本框值在路径URI路径中传递。

修改

使用上面的代码,每次单击按钮并提交表单时,URL都将包含名称/.../John,因为我已对其进行了硬编码。

我想要达到的目的不是将名称硬编码为John。 URL中的名称将来自用户在文本框中输入的内容。例如如果用户输入的名称为Mike,则网址应为/.../Mike,依此类推,具体取决于用户文本框输入。

简单来说,我不想将值硬编码为John,而是愿意根据文本框输入使其动态化。

请让我知道如何做到这一点。

此致

1 个答案:

答案 0 :(得分:1)

您正尝试路由到尚未指定的用户名的URL。

在页面加载时,当用户未指定John作为名称时,Play不知道您想要hello / name / John。

为了让您执行类似的操作,您可能希望在提交时使用javascript更改表单操作网址,以将操作网址替换为/name/(value of myName input field)

或者,您可以将其拆分为两个单独的控制器操作。

路线:

POST /greet  Application.greet
GET  /users/{myName}  Application.hello

Application.java

// accepts the form request with the myName paramater
public static void greet(String myName) {
    // redirects the user to /users/{myName}
    Application.hello(myName);
}

// welcomes the user by name
public static void hello(String myName) {
    render(myName);
}

查看模板:

<-- this url should be /greet  (noted we are submitting via POST) -->
<form action="@{Application.greet()}" method="post">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>