玩! framework - 处理POST请求

时间:2012-08-21 16:22:01

标签: java http web playframework-2.0 web-development-server

这是处理登录POST请求的路由:

POST  /login/submit                 controllers.Users.loginSubmit(user : String, password : String)

这是login.scala.html:

<form method="post" action="???">
  <input type="text" name="username" /><br/>
  <input type="password" name="password" /><br/>

  <input type="submit" value="Login" />
</form>

我有两个问题:

  1. 行动的价值应该是什么?是“登录/提交”?
  2. 如何传递此表单以在loginSubmit函数中处理?
  3. 感谢

2 个答案:

答案 0 :(得分:25)

如果是POST表单,则无需在route中声明参数:

POST  /login/submit           controllers.Users.loginSubmit()

模板:

<!-- syntax: @routes.ControllerName.methodName() -->
<form method="post" action="@routes.Users.loginSubmit()">
  <input type="text" name="username" /><br/>
  <input type="password" name="password" /><br/>

  <input type="submit" value="Login" />
</form>

导入:

import play.data.DynamicForm;
import play.data.Form;

控制器:

public static Result loginSubmit(){
    DynamicForm dynamicForm = Form.form().bindFromRequest();
    Logger.info("Username is: " + dynamicForm.get("username"));
    Logger.info("Password is: " + dynamicForm.get("password"));
    return ok("ok, I recived POST data. That's all...");
}

模板表单助手

还有form template helpers可用于在Play模板中创建表单,因此可以这样做:

@helper.form(action = routes.User.loginSubmit()) {
    <input type="text" name="username" /><br/>
    <input type="password" name="password" /><br/>

    <input type="submit" value="Login" />
}

在处理大型和/或pre-filled表单

时,它们特别有用

答案 1 :(得分:3)

在Play Framework版本2.5.x Form.form() is deprecated中,您应该使用inject a FormFactory

您可以在这里找到示例:The method form(Class) from Form class is deprecated in Play! Framework

导入:

import play.data.DynamicForm;
import play.data.FormFactory;

注入:

@Inject FormFactory formFactory;

控制器:

public static Result loginSubmit(){
    DynamicForm dynamicForm = formFactory.form().bindFromRequest();
    Logger.info("Username is: " + dynamicForm.get("username"));
    Logger.info("Password is: " + dynamicForm.get("password"));
    return ok("ok, I recived POST data. That's all...");
}