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

时间:2016-01-13 10:52:34

标签: java playframework playframework-2.4

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

  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
  4. 但是没有任何事情发生, play2.4.6 仍然会在devNotFound.scala.html playframework 源文件夹中的framework/play/src/main/scala/views/defaultpages/内用完默认页面

    请帮忙。

3 个答案:

答案 0 :(得分:2)

在Play 2.4.x中执行此操作的方法是使用此处记录的HttpErrorHandler

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

您可以扩展DefaultHttpErrorHandler并添加返回自定义页面:

  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
  3. 以下是一个完整的示例,考虑到您正在尝试覆盖默认的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"
    

答案 1 :(得分:1)

public class Global extends GlobalSettings {

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

答案 2 :(得分:0)

enter image description here

    @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中。