我刚开始玩框架游戏。我能够通过请求直接发送简单的数据类型,如字符串、整数等,并在后端Java方法中访问它们。
当我尝试在路由文件中这样做时,
GET /food/fetchMealInfo/:noOfDays/:dateSelected controllers.trackandplan.FoodController.fetchMealInfo(noOfDays : Integer, dateSelected : Date)
我说错了
Compilation error
not found: type Date
如何正确、安全和干净地将日期对象从前端AngularJS应用程序传输到Play框架中的Java应用程序?请指点。
发布于 2015-05-06 06:28:11
你有几个选择。稍微容易理解的方法是简单地将日期/时间作为Long
(unix时间戳)传输,并在控制器方法中将其转换为Date
。
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());
...
}
更复杂的方法是使用PathBindable
,这将允许您在路由文件本身中使用Date
。但是,您仍然需要将Date
作为Long
传输(如果可能的话,PathBindable
将进行转换)。不幸的是,由于我们显然无法控制Date
,所以我们必须在Scala中实现PathBindable
,而不是Java (Java需要为Date
实现接口,而我们不能这样做)。
app/libs/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
}
}
为了使路由文件能够获得这一点,您需要在build.sbt
文件中添加以下内容:
PlayKeys.routesImport += "com.example.libs.PathBinders._"
PlayKeys.routesImport += "java.util.Date"
现在,您可以在路由文件中使用Date
(如Long
),而无需为使用它的每个方法专门处理它。
GET /food/fetchMealInfo/:noOfDays/:dateSelected controllers.trackandplan.FoodController.fetchMealInfo(noOfDays: Integer, dateSelected: Date)
注意:如果您使用的是旧的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)
}
}
发布于 2015-05-06 06:33:21
将其作为String
发送,并在操作中将其解析为Date
对象。
public static Result readDate(String date) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date dateObj = null;
try {
dateObj = format.parse(date);
} catch (ParseException e) {
debug(date + " is invalid date");
}
return (dateObj == null)
? badRequest("Invalid date format")
: ok(dateObj.toString()
);
}
可以在other question中找到更多从字符串中解析日期的示例。
https://stackoverflow.com/questions/30078615
复制相似问题