我是 Play 框架的新手。我正在开发一个基本项目,现在正在研究身份验证功能。我想将未经授权的用户重定向到/login 路由。
我发现 Global.java 类允许我控制整个项目的操作,特别是使用 onRequest 函数。我计划用它来进行重定向。
我在网上搜索了多种解决方案,但找不到有效的解决方案。
我的类(class):
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 不感兴趣,而且我不太明白这个问题。有人能帮助我吗 ?谢谢!
最佳答案
我已经有一段时间没有使用 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()));
}
关于java - Play框架2.X : Dealing w/onReqest and redirect in Global. java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29993925/