Java 如何在 Play Framework 中获取表单数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18470013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:53:07  来源:igfitidea点击:

How to get form data in Play Framework

javaplayframeworkplayframework-2.0

提问by Gandalf StormCrow

I found this neat post before asking this question (but doesn't solve my problem) :

在问这个问题之前,我发现了这个整洁的帖子(但没有解决我的问题):

I'm trying to update a record with ajax call using play framework as a backend.

我正在尝试使用播放框架作为后端使用 ajax 调用更新记录。

Here is some data regarding my request :

以下是有关我的请求的一些数据:

Request URL:http://172.20.12.50:9000/updateName
Request Method:PUT

Form Data
name=&value=Testttt&pk=367

enter image description here

在此处输入图片说明

Here is how I try to test what I get on the server side :

这是我尝试测试我在服务器端获得的内容的方法:

Logger.info("PK IS " + request().getQueryString("pk"));

This is what I get in the log:

这是我在日志中得到的:

[info] application - PK IS null

How would I get these params from FormData? I got this data regarding my request from firebug

我如何从 FormData 获取这些参数?我从萤火虫那里得到了关于我的请求的数据

采纳答案by mguillermin

The POST data is available in a controller with request().body().

POST 数据在带有request().body().

On the body, you can call .asFormUrlEncoded()to retrieve a Mapof the data. You will find more information in the documentation.

在正文上,您可以调用.asFormUrlEncoded()以检索Map数据。您将在文档中找到更多信息。

For more complex use cases, you can use the Form APIto define data constraints and validation and bind data directly to a specific class.

对于更复杂的用例,您可以使用Form API来定义数据约束和验证并将数据直接绑定到特定类。

回答by Chris Beach

Adapted from http://www.playframework.com/documentation/2.0/ScalaForms

改编自http://www.playframework.com/documentation/2.0/ScalaForms

import play.api.data._
import play.api.data.Forms._

case class MyFormData(name: Option[String], value: String, pk: Long)

val myForm = Form(
    mapping(
        "name" -> optional(text),
        "value" -> text,
        "pk" -> number
    )(MyFormData.apply)(MyFormData.unapply)
)

myForm.bindFromRequest.fold(
    formWithErrors => // binding failure, you retrieve the form containing errors,
    value => // binding success, you get the MyFormData value 
)

Obviously substitute MyFormDatafor something meaningful to your domain.

显然可以替代MyFormData对您的领域有意义的东西。

回答by Ducaz035

You can get it for files:

您可以为文件获取它:

val music = request.body.file("music").get

for body parts as an example:

以身体部位为例:

var tracktitle = ""
        request.body.dataParts.get("tracktitle").get.foreach(value => tracktitle = value)