jac*_*All 6 javascript java datetime get playframework
我是Play Framework的新手.我可以通过请求直接发送简单的数据类型,如字符串,整数等,并在后端Java方法中访问它们.
当我尝试在路径文件中执行此操作时,
GET /food/fetchMealInfo/:noOfDays/:dateSelected controllers.trackandplan.FoodController.fetchMealInfo(noOfDays : Integer, dateSelected : Date)
Run Code Online (Sandbox Code Playgroud)
我收到一个错误说
Compilation error
not found: type Date
Run Code Online (Sandbox Code Playgroud)
将日期对象从前端AngularJS应用程序传输到Play Framework中的Java应用程序是什么是正确,安全和干净的方法.请指导.
你有几个选择.稍微容易理解的方法是简单地将日期/时间作为Long(unix时间戳)传输,并将其转换Date为控制器方法中的a.
GET /food/fetchMealInfo/:noOfDays/:dateSelected controllers.trackandplan.FoodController.fetchMealInfo(noOfDays: Integer, dateSelected: Long)
public static Result fetchMealInfo(Integer noOfDays, Long dateSelected) {
Date date = new Date(dateSelected.longValue());
...
}
Run Code Online (Sandbox Code Playgroud)
更复杂的方法是使用a PathBindable,这将允许您Date在routes文件本身中使用.但是,您仍然需要传输Dateas Long(PathBindable如果可能,将进行转换).不幸的是,由于我们显然无法控制Date,我们必须PathBindable在Scala中实现,而不是Java(Java需要实现一个接口Date,我们不能).
应用程序/库/ PathBinders.scala
package com.example.libs
import java.util.Date
import play.api.mvc.PathBindable
import scala.util.Either
object PathBinders {
implicit def bindableDate(implicit longBinder: PathBindable[Long]) = new PathBindable[Date] {
override def bind(key: String, value: String): Either[String, Date] = {
longBinder.bind(key, value).right.map(new Date(_))
}
override def unbind(key: String, date: Date): String = key + "=" + date.getTime().toString
}
}
Run Code Online (Sandbox Code Playgroud)
为了使路径文件能够选择它,您需要将以下内容添加到您的build.sbt文件中:
PlayKeys.routesImport += "com.example.libs.PathBinders._"
PlayKeys.routesImport += "java.util.Date"
Run Code Online (Sandbox Code Playgroud)
现在,您可以Date在路径文件(as Long)中使用,而无需为使用它的每个方法专门处理它.
GET /food/fetchMealInfo/:noOfDays/:dateSelected controllers.trackandplan.FoodController.fetchMealInfo(noOfDays: Integer, dateSelected: Date)
Run Code Online (Sandbox Code Playgroud)
注意:如果您使用较旧的Play版本,则可能无法立即编译.我用Play 2.3.8和sbt 0.13.5测试了它.
也可以修改PathBindable我在这里使用底层String代替,并接受特定的日期格式.
package com.example.libs
import java.util.Date
import java.text.SimpleDateFormat
import play.api.mvc.PathBindable
import scala.util.{Either, Failure, Success, Try}
object PathBinders {
implicit def bindableDate(implicit stringBinder: PathBindable[String]) = new PathBindable[Date] {
val sdf = new SimpleDateFormat("yyyy-MM-dd")
override def bind(key: String, value: String): Either[String, Date] = {
for {
dateString <- stringBinder.bind(key, value).right
date <- Try(sdf.parse(dateString)).toOption.toRight("Invalid date format.").right
} yield date
}
override def unbind(key: String, date: Date): String = key + "=" + sdf.format(date)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7229 次 |
| 最近记录: |