2013-02-13 28 views
2
自定義404響應

當人們要求上沒有CSP文件夾中找到一個servlet 它會顯示一個「404未找到」響應爲金桂冠

未找到

所請求的URL不在此服務器上找到。

有沒有辦法我們可以檢查一個servlet是否存在,來創建自定義的404頁面?

回答

0

就像吉爾說的那樣。您可以使用HDL_HTTP_ERRORS來攔截HTTP錯誤。爲了更清楚地說明一個示例連接處理程序,它用自定義錯誤消息替換了404錯誤。

#include "gwan.h" 
int init(int argc, char *argv[]) 
{ 
    u32 *states = (u32*)get_env(argv, US_HANDLER_STATES); 
    *states = (1 << HDL_HTTP_ERRORS); 
    return 0; 
} 

int main(int argc, char *argv[]) 
{ 
    if((long)argv[0] != HDL_HTTP_ERRORS) 
     return 255; // Continue if not an error 

    // get the HTTP reply code 
    int *status = (int*)get_env(argv, HTTP_CODE); 
    if(!status || *status != 404) 
     return 255; // Continue if not a 404 error 

    static char custom_err[] = 
     "<!DOCTYPE HTML><html><head><title>404 Not Found</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><link href=\"/imgs/errors.css\" rel=\"stylesheet\" type=\"text/css\"></head>" 
     "<body><h1>Not Found</h1>" 
     "<p>This is a custom 404 not found error. What makes you think that this link exist?!!</p></body></html>"; 

    static char header[] = 
     "HTTP/1.1 %s\r\n" 
     "Server: G-WAN\r\n" 
     "Date: %s\r\n" 
     "Content-Type: text/html; charset=UTF-8\r\n" 
     "Content-Length: %u\r\n\r\n"; 

    int len = sizeof(custom_err)-1; 
    char *date = (char*)get_env(argv, SERVER_DATE); 
    // Set our http reply headers 
    build_headers(argv, header, 
      http_status(*status), 
      date, // current server date 
      len); // Reply length 

    // Set our reply using our custom error 
    set_reply(argv, custom_err, len, *status); 

    return 2; // End request then send reply 
} 

void clean(int argc, char *argv[]) {} 

請注意,如果您從servlet返回404錯誤。確保你做了一個

xbuf_empty(get_reply(argv)); 

清空答覆緩衝區的內容。如果回覆緩衝區中有任何內容,它將不會到達HDL_HTTP_ERRORS。它只會回覆任何答覆緩衝區。

0

Both 內容類型和連接處理程序可以在服務之前檢查資源是否存在。

HDL_HTTP_ERRORS狀態連接處理程序可以攔截HTTP錯誤以更改由G-WAN生成的默認答覆。它在記錄的G-WAN API Handler States中定義。

這很可能是你在找什麼。