2016-10-21 49 views
0

在我的JEE應用,在GlassFish 3運行,我有以下情況:JEE:如何參數傳遞給攔截

MyFacade類

@Interceptors(SomeInterceptor.class) 
public void delete(Flag somethingForTheInterceptor, String idToDelete) { 
    ....... 
} 

@Interceptors(SomeInterceptor.class) 
public void update(Flag somethingForTheInterceptor, MyStuff newStuff) { 
    ....... 
} 

變量somethingForTheInterceptor不使用這些方法中,僅在使用攔截器:

SomeInterceptor類

@AroundInvoke 
public Object userMayAccessOutlet(InvocationContext ctx) throws Exception { 
    Flag flag = extractParameterOfType(Arrays.asList(ctx.getParameters()), Flag.class); 
    // some checks on the flag 
} 

不知何故,它不舒服有一個參數,沒有在方法中使用。有沒有另外一種方法將「somethingForTheInterceptor」發送給攔截器?

UPDATE:的delete()update()的呼叫者具有計算somethingForTheInterceptor變量的不同方式。這不是一個常數。計算它所需的信息在REST調用中。但是2個REST方法有不同的輸入對象,所以僅僅注入http請求是不夠的。

這些求助者:

MyResource類

@DELETE 
@Path("/delete/{" + ID + "}") 
public Response delete(@PathParam(ID) final String id) { 
    Flag flag = calculateFlagForInterceptor(id); 
    facade.delete(flag, id); 
} 

@POST 
@Path("/update") 
@Consumes(MediaType.APPLICATION_JSON + RestResourceConstants.CHARSET_UTF_8) 
public Response update(final WebInputDTO updateDetails) throws ILeanException { 
    Flag flag = calculateFlagForInterceptor(updateDetails); 
    facade.update(flag, convertToMyStuff(updateDetails)); 
} 

我在想 - 這可能在資源的方法設置在某種語境下的標誌,可以被後來注入攔截器?

+0

這個標誌值可能是什麼?它可能是註釋中的一個常量嗎?你能解釋這個標誌的需要嗎? – AxelH

回答

1

在Java EE中,攔截器允許將前處理和後處理添加到方法中。 因此,攔截器執行的上下文是該方法的上下文。

我在想 - 這可能在資源的方法來設置 標誌在某種語境的,可以在以後的 攔截注入?

Staless服務應該有特權時,您可以。所以,你應該避免在服務器上存儲數據(ThreadLocal,Session等)。

在REST調用中計算它所需的信息是 。

爲什麼? 休息控制器沒有職業去做計算和邏輯。

爲了解決你的問題,你確定你不能在攔截器中移動標誌計算嗎? 通過增強攔截器的職責,您不需要更長的時間來傳輸標誌:

@AroundInvoke 
public Object userMayAccessOutlet(InvocationContext ctx) throws Exception { 
    Flag flag = calculFlag(Arrays.asList(ctx.getParameters())); 
    // some checks on the flag 
} 
+0

謝謝,我接受了這個答案,因爲它指出替代解決方案可能會帶來一些弊端。最好的解決方案是在攔截器中實現'calculateFlag()'方法,這不是不可能的。 – user1414745

+0

不客氣。在這種情況下,攔截器可能不是最適合您需求的模式。 – davidxxx

相關問題