Play! framework - handle a POST request

自古美人都是妖i 提交于 2019-12-22 04:36:27

问题


this is the route to handle the login POST request:

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

this is the 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>

I got two questions:

  1. what should be the value of action? is it "login/submit"?
  2. how do you pass this form to be handled in the loginSubmit function?

thanks


回答1:


If it's POST form, you don't need to declare params in the route:

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

Template:

<!-- 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:

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

Controller:

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...");
}

Template form helpers

There are also form template helpers available for creating forms in Play's template so the same can be done as:

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

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

They are especially useful when working with large and/or pre-filled forms




回答2:


In Play Framework version 2.5.x Form.form() is deprecated and you should use inject a FormFactory

Here you can find example: The method form(Class) from Form class is deprecated in Play! Framework

Import:

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

Inject:

@Inject FormFactory formFactory;

Controller:

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...");
}


来源:https://stackoverflow.com/questions/12059147/play-framework-handle-a-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!