2013-11-01 56 views
5

有谁知道如何用覆盖现在404错误页面使用时Spark微网框架?SparkJava自定义错误页面

默认错误页面是:

<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"; 
    } 
}); 

回答

2

您可以在Web服务器上将应用映射到火花路径。

<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> 
0

我想你可以使用一个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"); 
     } 
    } 
}); 
+0

问题'公共目录'。由于公共目录(它引发Jetty 404错误页面),所以过滤每个url路径是不可能的。 – dns

3

尝试使用下面

这个提示添加这些行最后的路线之后,因为星火在乎为了

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

所有请求(包括静态请求)不匹配的所有航线上这将在这里被捕获。所以,你必须用IF语句分隔奇怪的请求和静态请求。你应该在这里返回你的错误html页面作为字符串。

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

+0

错误:(214,35)-source 1中不支持java:lambda表达式。6 (使用-source 8或更高来启用lambda表达式) – dns

+0

当我将目标更改为8时,它将返回:错误:java:javacTask:源版本8需要目标版本1.8 – dns

+0

我是否需要重新构建所有外部依赖项(如Jetty,servlet,freemarker,slf4j,spark-core)为1.8? – dns

1

在星火2.3文档:

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

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

我发现,而不是 “/ throwexception”, “/ *” 被所有找不到的网页。如果你的网址结构比我所做的更复杂,这可能不起作用。我无法解决我的项目中的NotFoundException,所以我认为你可以创建自己的异常或者内置一个异常。

1

对于那些谁想要来处理所有的异常,并显示后面的错误消息,这里有一个简单的方法来声明处理器:

exception(Exception.class, exceptionHandler()); 

,然后一个简单的实现:

private ExceptionHandler exceptionHandler() { 
    return (e, req, res) -> { 
     res.status(500); 
     res.body("<h1>Exception occurred</h1><div>" + e.getMessage() + "</div>"); 
    }; 
}