scala 如何使用 Play 2.0 创建自定义 404 页面处理程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9989444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:03:53  来源:igfitidea点击:

How to create a custom 404 page handler with Play 2.0?

scalaplayframework-2.0

提问by Julien Richard-Foy

What's the preferred way to handle 404 errors with Play 2.0 and show a nice templated view?

使用 Play 2.0 处理 404 错误并显示漂亮的模板化视图的首选方法是什么?

采纳答案by Julien Richard-Foy

You can override the onHandlerNotFoundmethod on your Globalobject, e.g.:

您可以覆盖对象onHandlerNotFound上的方法Global,例如:

object Global extends GlobalSettings {
  override def onHandlerNotFound(request: RequestHeader): Result = {
    NotFound(views.html.notFound(request))
  }
}

回答by Andrew E

Please note that there are really two different problems to solve:

请注意,实际上有两个不同的问题需要解决:

  1. Showing a custom 404 page when there is "no handler found", e.g. when the user goes to an invalid URL, and

  2. Showing a custom 404 (NotFound) page as a valid outcome of an existing handler.

  1. 在“未找到处理程序”时显示自定义 404 页面,例如当用户访问无效 URL 时,以及

  2. 将自定义 404 (NotFound) 页面显示为现有处理程序的有效结果。

I think the OP was referring to #2 but answers referred to #1.

我认为 OP 指的是 #2,但答案指的是 #1。

"No Handler Found" Scenario

“未找到处理程序”场景

In the first scenario, for "no handler found" (i.e. invalid URL), the other answers have it right but to be more detailed, per the Play 2.1 documentationas:

在第一种情况下,对于“未找到处理程序”(即无效的 URL),其他答案是正确的,但更详细,根据Play 2.1 文档如下:

Step 1: add a custom Global object:

第 1 步:添加自定义 Global 对象:

import play.api._
import play.api.mvc._
import play.api.mvc.Results._

object Global extends GlobalSettings {

  override def onHandlerNotFound(request: RequestHeader): Result = {
    NotFound(
      views.html.notFoundPage(request.path)
    )
  }   
}

Step 2: add the template. Here's mine:

第二步:添加模板。这是我的:

@(path: String)

<html>
<body>
<h1>Uh-oh. That wasn't found.</h1>
<p>@path</p>
</body>
</html>

Step 3: tweak your conf/application.conf to refer to your new "Global". I put it in the controllers package but it doesn't have to be:

第 3 步:调整您的 conf/application.conf 以引用您的新“全局”。我把它放在控制器包中,但它不一定是:

...
application.global=controllers.Global

Step 4: restart and go to an invalid URL.

第 4 步:重新启动并转到无效的 URL。

"Real Handler can't find object" Scenario

“Real Handler 找不到对象”场景

In the second scenario an existing handler wants to show a custom 404. For example, the user asked for object "1234" but no such object exists. The good news is that doing this is deceptively easy:

在第二种情况下,现有处理程序想要显示自定义 404。例如,用户请求对象“1234”但不存在此类对象。好消息是,这样做看似简单:

Instead of Ok(), surround your response with NotFound()

而不是 Ok(),用 NotFound() 包围你的响应

For example:

例如:

object FruitController extends Controller {

  def showFruit(uuidString: String) = Action {
    Fruits.find(uuidString) match {
      case Some(fruit) => Ok(views.html.showFruit(fruit))

      // NOTE THE USE OF "NotFound" BELOW!
      case None => NotFound(views.html.noSuchFruit(s"No such fruit: $uuidString"))
    }
  }
}

What I like about this is the clean separation of the status code (200 vs 404) from the HTML returned (showFruit vs noSuchFruit).

我喜欢这一点的是状态代码(200 对 404)与返回的 HTML(showFruit 对 noSuchFruit)的清晰分离。

HTH Andrew

HTH安德鲁

回答by Miguel A. Carrasco

If you want to do the same using Java instead of Scala you can do it in this way (this works for play framework 2.0.3):

如果你想使用 Java 而不是 Scala 来做同样的事情,你可以这样做(这适用于播放框架 2.0.3):

Global.java:

全局.java:

import play.GlobalSettings;
import play.mvc.Result;
import play.mvc.Results;
import play.mvc.Http.RequestHeader;


public class Global extends GlobalSettings {

    @Override
    public Result onHandlerNotFound(RequestHeader request) {
        return Results.notFound(views.html.error404.render());
    }
}

Asumming that your 404 error template is views.html.error404 (i.e. views/error404.scala.html).

假设您的 404 错误模板是 views.html.error404(即 views/error404.scala.html)。

回答by Shanker Kaura

This works in 2.2.1. In Global.java:

这适用于 2.2.1。在 Global.java 中:

public Promise<SimpleResult> onHandlerNotFound(RequestHeader request) {
    return Promise.<SimpleResult>pure(notFound(
        views.html.throw404.render()
    ));
}

Ensure that you have a view called /views/throw404.scala.html

确保您有一个名为 /views/throw404.scala.html

回答by Tom

Please note that Play development team are making lots of efforts to move away from global state in Play, and hence GlobalSettingsand the application Global object have been deprecated since version 2.4.

请注意,Play 开发团队正在努力摆脱 Play 中的全局状态,因此GlobalSettings自 2.4 版以来,应用程序 Global 对象已被弃用。

HttpErrorHandler.onClientErrorshould be used instead of GlobalSettings.onHandlerNotFound. Basically create a class that inherits from HttpErrorHandler, and provide an implementation for onClientErrormethod.

HttpErrorHandler.onClientError应该使用而不是 GlobalSettings.onHandlerNotFound. 基本上创建一个继承自 的类HttpErrorHandler,并提供onClientError方法的实现。

In order to find out type of error (404 in your case) you need to read status code, which is passed as a one of the method arguments e.g.

为了找出错误类型(在您的情况下为 404),您需要阅读状态代码,该代码作为方法参数之一传递,例如

if(statusCode == play.mvc.Http.Status.NOT_FOUND) {
    // your code to handle 'page not found' situation 
    // e.g. return custom implementation of 404 page
}

In order to let Play know what handler to use, you can place your error handler in the root package or configure it in application.conf using play.http.errorHandlerconfiguration key e.g.

为了让 Play 知道要使用什么处理程序,您可以将错误处理程序放在根包中或使用play.http.errorHandler配置键在 application.conf 中配置它,例如

play.http.errorHandler = "my.library.MyErrorHandler"

You can find more details on handling errors here: for Scalaor Java.

您可以在此处找到有关处理错误的更多详细信息:对于ScalaJava

回答by Jaanus

For Java, if you want to just redirect to main page, I solved it by this.

对于 Java,如果你只想重定向到主页,我通过这个解决了它。

@Override
public Promise<Result> onHandlerNotFound(RequestHeader request) {
    return Promise.pure(redirect("/"));
}

回答by Sivailango

This works in 2.2.3 Play - Java

这适用于 2.2.3 Play - Java

public Promise<SimpleResult> onHandlerNotFound(RequestHeader request) {
    return Promise<SimpleResult>pure(Results.notFound(views.html.notFound404.render()));
}

html should be within /views/notFound404.scala.html Dont forget to add Results.notFounf() and import play.mvc.Results;

html 应该在 /views/notFound404.scala.html 内 不要忘记添加 Results.notFounf() 并导入 play.mvc.Results;