SparkJava自定义错误页面

6

有人知道在使用 Spark 微框架时如何覆盖现有的404错误页面吗?

默认的错误页面是:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 404 </title>
</head>
<body>
<h2>HTTP ERROR: 404</h2>
<p>Problem accessing /strangepage. Reason:
<pre>    Not Found</pre></p>
<hr /><i><small>Powered by Jetty://</small></i>
</body>
</html>

我想编辑这个“自定义”错误页面(或者将其重定向到另一个路由):
get(new Route("/404") {
   @Override
   public Object handle(Request request, Response response) {
       response.type("text/html");
       return "Error page 404";
   }
});
7个回答

4

尝试使用以下提示:

在最后一个路由之后添加这些行,因为Spark在意顺序。

Spark.get("*", (req, res) -> {    
    if(!req.pathInfo().startsWith("/static")){
        res.status(404);
        return TEMPLATE_ENGINE.render(ModelAndView modelAndView);
    }
    return null;
});

所有请求(包括静态请求)都不匹配所有上层路由,这里将被捕获。因此,您必须使用IF语句分离奇怪的请求和静态请求。您应该将错误的HTML页面作为字符串返回。

所有静态请求都由另一个处理程序处理,您必须返回NULL以强制Spark调用另一个处理程序作为正常情况。


错误:(214,35)java:不支持lambda表达式-源1.6 (使用-source 8或更高版本启用lambda表达式) - dns
当我将目标更改为8时,它返回:错误:java:javacTask:源发布8需要目标发布1.8 - dns
我需要重新构建所有外部依赖项(例如Jetty,servlet,freemarker,slf4j,spark-core)以适用于1.8吗? - dns
请问您使用的是哪个IDE和构建工具? - Ken Block

3
这是一个老问题,但由于它仍然得到了回答。
现在您可以按如下方式处理404错误页面:
notFound("<html><body><h1>Custom 404 handling</h1></body></html>");

谢谢。已经过去5年了。Spark开发人员似乎很慢才能修复这个基本的未实现功能。还有其他未实现的基本HTTP规范,Spark开发人员决定忽略它。 - dns
这个方法也接受一个路由参数,以防您想设置内容类型:notFound((req, res) -> ...) - z0r

3

对于希望处理所有异常并显示错误消息的人,这里有一种简单的声明处理程序的方法:

exception(Exception.class, exceptionHandler());

然后是一个简单的实现:
private ExceptionHandler exceptionHandler() {
    return (e, req, res) -> {
        res.status(500);
        res.body("<h1>Exception occurred</h1><div>" + e.getMessage() + "</div>");
    };
}

2

如果您将应用部署在Web服务器上,可以将错误映射到Spark路由。

<filter>
    <filter-name>SparkFilter</filter-name>
    <filter-class>spark.servlet.SparkFilter</filter-class>
    <init-param>
        <param-name>applicationClass</param-name>
        <param-value>com.company.YourApplication</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>SparkFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

<error-page>
    <error-code>404</error-code>
    <location>/404</location> <!-- this is your route-->
</error-page>

1
在Spark 2.3文档中:

get("/throwexception", (request, response) -> {
    throw new NotFoundException();
});

exception(NotFoundException.class, (e, request, response) -> {
    response.status(404);
    response.body("Resource not found");
});

我发现,与"/throwexception"不同,"/*"可以获取所有未找到的页面。如果您的URL结构比我所做的更复杂,则可能无法正常工作。我在项目中无法解决NotFoundException,因此我认为您可以创建自己的异常或抛出内置异常。

1
我认为你可以使用Spark过滤器。用于过滤不允许的路由。你可以在过滤器中渲染一个新的模板。
这是文档中的一个例子。
before(new Filter() { // matches all routes
    @Override
    public void handle(Request request, Response response) {
        boolean authenticated;
        // ... check if authenticated
        if (!authenticated) {
            halt(401, "You are not welcome here");
        }
    }
 });

问题出在“public目录”。由于该目录会抛出Jetty 404错误页面,因此无法过滤每个URL路径。 - dns

1

请在您的问题中添加相关代码。如果您不小心删除了Github,答案将变得无用 :) - Alfabravo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接