我是Play Framework的新手。我正在从事一个基础项目,现在正在使用身份验证功能。我想将未经授权的用户重定向到/ login路由。
我发现了Global.java类,它允许我控制我的项目中的操作,特别是onRequest函数。我计划用它来进行重定向。
我在网上搜索了几个解决方案,但我找不到合适的解决方案。
我的课程:
import play.*;
import play.mvc.Action;
import play.mvc.*;
import play.mvc.Http.*;
import play.mvc.Result.*;
import play.libs.F.*;
import static play.mvc.Results.*;
import play.mvc.Http.Request;
import java.lang.reflect.Method;
public class Global extends GlobalSettings {
@Override
public Action onRequest(Request request, Method actionMethod) {
//Check if the user is connected
if (request.cookie("PLAY_SESSION") == null && !request.path().startsWith("/login")) {
System.out.println("UNAUTHORIZED");
return new Action.Simple() {
@Override
public Result call(Context ctx) throws Throwable {
return redirect(controllers.routes.Application.index());
}
};
}
return super.onRequest(request, actionMethod);
}
}
我找到了这个,我不明白为什么玩!不想编译:
error: <anonymous Global$1> is not abstract and does not override abstract method call(Context) in Action
error: method does not override or implement a method from a supertype
我不会随意玩Play,我也不会真正理解这个问题。有谁可以帮助我吗 ?谢谢!
答案 0 :(得分:3)
我现在还没有使用Play Framework一段时间,但我认为问题是在2.2中他们让Action返回Promise而不仅仅是Result。因此有你的问题。
检查与之匹配的Action.Simple.call()版本
Result call(Context ctx) throws Throwable
查看
之间的区别https://www.playframework.com/documentation/2.2.x/api/java/index.html https://www.playframework.com/documentation/2.1.x/api/java/index.html
(查看调用方法的返回类型)
修改强>
我不确定这是否是最佳方法,但它应该有效。
@Override
public F.Promise<Result> call(Context ctx) throws Throwable {
return F.Promise.pure(redirect(controllers.routes.Application.index()));
}
答案 1 :(得分:0)
F.Promise.pure()可用于将Result(或实现它的任何内容,例如Results.Status)转换为Promise。
示例,其中ok()返回play.mvc.Results.Status:
F.Promise.pure(ok("[No Preview Available]"));