本文是在Play2.1下進行的,不過很可能也适合Play2的各個版本。
=======================================
play2.1的業務操作傳回資訊可以使用Ajax的結果由alert向使用者展示。
如果需要這種方法,可以參考
http://somefuture.iteye.com/blog/1983621(請一定注意:這種方法僅僅适合于Play!2.1,其他版本幾乎是不可能這樣做的。)
我寫了一個通用方法,可以進行增删改:
import java.util.concurrent.Callable;
import play.db.jpa.JPA;
import play.libs.F.Function;
import play.libs.F.Function0;
import play.libs.F.Promise;
import play.mvc.Result;
import play.mvc.Results;
public class AsyncTransanctionUtil{
public static final Integer PERSIST = 1;
public static final Integer MERGE = 2;
public static final Integer REMOVE = 3;
public static Result asyncResult(final Integer type, final Object object) {
Promise<Boolean> promiseOfInt = play.libs.Akka
.future(new Callable<Boolean>() {
public Boolean call() {
if (type == PERSIST) {
try {
JPA.withTransaction(new Function0<Void>() {
@Override
public Void apply() throws Throwable {
JPA.em().persist(object);
return null;
}
});
} catch (Throwable e) {
return false;
}
}else if (type == MERGE) {
try {
JPA.withTransaction(new Function0<Void>() {
@Override
public Void apply() throws Throwable {
JPA.em().merge(object);
return null;
}
});
} catch (Throwable e) {
return false;
}
}else if (type == REMOVE) {
try {
JPA.withTransaction(new Function0<Void>(){
public Void apply() throws Throwable {
Object obj = JPA.em().merge(object);
JPA.em().remove(obj);
return null;
};
});
} catch (Throwable e) {
return false;
}
}
return true;
}
});
return Results.async(promiseOfInt.map(new Function<Boolean, Result>() {
public Result apply(Boolean result) {
if (result) {
return Results.ok("success");
}else {
return Results.badRequest("fail");
}
}
}));
}
}
==========================================以上是異步處理
Play還可以使用flash進行操作提示。
業務處理結束後,通過一句即可
flash("success", "完成了,啊哈哈哈");
比如:
@Transactional
public static Result deletedp(Long sid, Long pid){
Deployment deployment = (Deployment) JPA.em()
.createQuery("from Deployment where sid=? and pid=?")
.setParameter(1, sid).setParameter(2, pid).getResultList()
.get(0);
// return AsyncTransanctionUtil.asyncResult(AsyncTransanctionUtil.REMOVE, deployment);
JPA.em().remove(deployment);
flash("success", "呃,就這樣吧,主公快走");
return redirect("/index");
}
這樣頁面會收到flash資訊。
因為flash資訊是一種HTTP内容,儲存進了cookie中:
package play.mvc;
import java.io.*;
...
/**
* Defines HTTP standard objects.
*/
public class Http {
...
/**
* HTTP Flash.
* <p>
* Flash data are encoded into an HTTP cookie, and can only contain simple String values.
*/
public static class Flash extends HashMap<String,String>{...}
...
}
上面是Flash類的定義。
頁面的擷取方式很簡單:
@if(flash.containsKey("success")){
<div>
@flash.get("success")
</div>
}
把想要展示的東西if出來就行。
======================存在的問題:
如果從該頁面跳轉後再傳回來,由于不是重新請求,flash資訊依然存在也會顯示出來。