2013-11-01 97 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>"); 
    }; 
}