将动态值传递给路由 URI



我正在尝试根据文本框的内容将动态值发送到路由 URI 路径,但当我尝试时,它显示为空值。

这是我尝试过的:

<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 URL 等。

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

请让我知道该怎么做。

问候

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

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

为了像你想做的那样做一些事情,你需要使用 javascript 在提交时更改表单操作 url,以将操作 url 替换为 /name/(value of myName input field)

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

路线:

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

应用.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>

最新更新