2017-09-02 29 views
0

響應我有一個資源:如何獲得內容類型JAX-RS ExceptionMapper

@GET 
@Path("/print-order") 
@Produces("application/pdf") 
public byte[] printOrder(@QueryParam("id") Long orderId) { 
    return ...; 
} 

...它可以拋出一個錯誤,是有關用戶和必須顯示爲一個HTML頁面。所以我實現了一個ExceptionMapper,但我不知道如何獲得被調用資源的註釋值@Produces("application/pdf")

@Provider 
public class CustomExceptionMapper implements ExceptionMapper<CustomException> { 
    @Override 
    public Response toResponse(CustomException exception) { 
     if (contentType = "application/pdf") 
      ... html respone 
     else 
      ... entity response 
    } 
} 

我使用JAX-RS的1.x(JSR311)與Jersy 1.12實現,但很想有實現獨立的解決方案。

回答

0

您可以將不同的上下文對象注入ExceptionMapper以獲取有關其處理的請求的更多信息。根據HTTP的Accept標題確定客戶端期望的內容類型很方便(詳細瞭解here)。

下面是關於如何使ExceptionMapper根據您的API客戶端指定(或未指定)的Accept頭以不同格式做出響應的示例。

@Provider 
public class CustomExceptionMapper implements ExceptionMapper<CustomException> { 

    // Inject headers of the request being processed 
    @Context 
    private HttpHeaders headers; 

    // or even all the request details 
    @Context 
    private HttpServletRequest request; 

    @Override 
    public Response toResponse(CustomException exception) { 
     List<MediaType> acceptedTypes = headers.getAcceptableMediaTypes(); 
     if (acceptedTypes.contains(MediaType.APPLICATION_JSON)) { 
     // respond with entity 
     } else { 
     // respond with HTML 
     } 
    } 
} 

雖然你最初的想法是可以實現的。您可以在資源分類中注入HttpServletRequest,並使用setAttribute()方法在當前請求的上下文中存儲application/pdf字符串。它可以在ExceptionMapper後面使用getAttribute()方法獲得。 但我不會推薦這樣做,除非絕對必要。它引入了代碼組件之間不太明顯的依賴關係。

+0

感謝您的詳細回覆,但這不是我所問的。我沒有接受標題,因爲它不是獲取請求,而是新窗口鏈接。我已經有了一個基於資源路徑的臨時修訂,所以建議的setAttribute只是更多的工作。 –