PlayFramework2 中的自定义错误页面。4.x

Custom Error Page in PlayFramework2.4.x

我做了这些但仍然看不到我的自定义页面,请帮忙,

  1. 已添加MyGlobal.java extends GlobalSettings

  2. 添加了 onHandlerNotFound 覆盖:

    @Override public F.Promise<Result> onHandlerNotFound(RequestHeader request) { Logger.error("onHandlerNotFound!"); return Promise.<Result> pure(Results.internalServerError(views.html.page404.render())); }

  3. 已添加application.global = "MyGlobal" in application.conf

但没有任何反应,play2.4.6 仍然运行 devNotFound.scala.htmlplayframework 源文件夹中的默认页面 framework/play/src/main/scala/views/defaultpages/

请帮忙。

public class Global extends GlobalSettings {

    @Override
    public Promise<SimpleResult> onHandlerNotFound(RequestHeader request) {
        return Promise.<SimpleResult>pure(internalServerError(views.html.page404.render()));
    }
}

Play 2 中的方法4.x 是使用此处记录的 HttpErrorHandler

https://www.playframework.com/documentation/2.4.x/JavaErrorHandling

您可以扩展 DefaultHttpErrorHandler 并添加 return 您的自定义页面:

  1. https://www.playframework.com/documentation/2.4.x/JavaErrorHandling#Extending-the-default-error-handler
  2. https://www.playframework.com/documentation/2.4.x/api/java/play/http/DefaultHttpErrorHandler.html

这是一个完整的示例,考虑到您正在尝试覆盖默认的 404 页面:

package com.acme.controllers.handlers;

import play.*;
import play.api.OptionalSourceMapper;
import play.api.UsefulException;
import play.api.routing.Router;
import play.http.DefaultHttpErrorHandler;
import play.libs.F.*;
import play.mvc.Http.*;
import play.mvc.*;

import javax.inject.*;

public class ErrorHandler extends DefaultHttpErrorHandler {

    @Inject
    public ErrorHandler(Configuration configuration, Environment environment,
                        OptionalSourceMapper sourceMapper, Provider<Router> routes) {
        super(configuration, environment, sourceMapper, routes);
    }

    @Override
    protected Promise<Result> onNotFound(RequestHeader request, java.lang.String message) {
      Logger.error("onHandlerNotFound!");
      return Promise.pure(Results.internalServerError(views.html.page404.render()));
    }
}

然后,您需要像这样在 conf/application.conf 中配置:

play.http.errorHandler = "com.acme.controllers.handlers.ErrorHandler"

    @Override
protected F.Promise<Result> onNotFound(RequestHeader request, String message) {
    Logger.debug("onNotFound: " + message);
    return Promise.<Result> pure(Results
            .ok(views.html.admin.page404.render(request.method(), request.uri())));
}

感谢您的帮助,它在开发环境中确实有效..

我已经有了 MyErrorHandler.java 但没有覆盖 onNotFound 函数,因为我几乎迷失在扩展 GlobalSettings 的 onHandlerNotFound 中。