2009-02-26 18 views

回答

2

我不認爲這是一個好主意。服務層不應該知道或關心它是否處理HTTP客戶端。

靜態聽起來不像正確的想法。 HttpRequestContext應該與HttpRequest實例關聯,而不是特定的類。

一個更好的設計,在我看來,會從上下文中獲取任何需要的服務並將其傳入。無需將服務耦合到HTTP或Web層。

+0

出色答卷 – 2009-02-27 04:49:45

+10

而不是總抱怨糟糕的編程風格,你能不能回答這個問題?我的意思是,你可以回答這個問題,然後抱怨不好的風格,但你根本不回答。 -1 – 2016-12-08 15:47:49

26

如果你正在使用Spring,你可以做到以下幾點:

public static HttpServletRequest getCurrentHttpRequest(){ 
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); 
    if (requestAttributes instanceof ServletRequestAttributes) { 
     HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest(); 
     return request; 
    } 
    logger.debug("Not called in the context of an HTTP request"); 
    return null; 
} 
相關問題