2015-08-27 381 views
0

下面是一個簡單的Web應用程序,配置爲在glassfish4上運行的Rest服務。該應用程序本身工作,可以訪問單個資源。java攔截器不攔截

攔截器不能用於pong(),但魔法般地爲helloW()工作。當我爲helloW()激活時,我可以修改和覆蓋參數,可以拋出異常等等。但是,這對pong()不起作用。在其他地方,我嘗試了無狀態的ejb - 相同的結果 - 不工作 - 即使使用ejb-jar程序集綁定部署描述符。爲什麼?

休息:

package main; 

import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 

@Path("/service") 
@javax.ejb.Stateless 
public class Service { 

    @GET 
    @Produces("text/plain") 
// @javax.interceptor.Interceptors({Intercept.class}) 
    public String helloW(String ss){ 

     String msg = pong("QQ"); 

     return msg; 
     //return ss; 
    } 

    @javax.interceptor.Interceptors({Intercept.class}) 
    public String pong(String m){ 
     String temp = m; 
     return temp; 
    } 
} 

攔截器本身:

package main; 

@javax.interceptor.Interceptor 
public class Intercept { 

    @javax.interceptor.AroundInvoke 
    Object qwe(javax.interceptor.InvocationContext ctx) throws Exception{ 

     ctx.setParameters(new Object[]{"intercepted attribute"}); 
     throw new Exception(); 
//  return ctx.proceed(); 
    } 
} 

是的,我曾嘗試與beans.xml的:

<interceptors><class>main.Intercept</class></interceptors> 

沒有喜悅。

回答

1

免責聲明:這是一個猜測,因爲我沒有找到任何關於此的支持文檔,它也可能取決於服務器的/ JRE實現

它不起作用,因爲@GET註釋的方法被使用java反射/內省技術調用。這避免了攔截該調用的框架,因爲它直接在JRE內完成。

爲了證明這一點,而不是調用「傍」直接作爲你在做嘗試以下方法:

try { 
    String msg = (String) this.getClass().getDeclaredMethod("pong", String.class).invoke(this, ss); 
    } catch (IllegalAccessException e) { 
    e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
    e.printStackTrace(); 
    } catch (NoSuchMethodException e) { 
    e.printStackTrace(); 
    } 

只需更換String msg = pong("QQ");爲您的樣品中的代碼。

您應該看到pong方法現在不像helloW那樣被攔截。

這個我能想到的唯一的工作圓是你已經做了:提取另一個非註釋方法內的邏輯。

+0

謝謝。我想現在應該足夠了。我的參考資料是oracle javaee tutorial和ejb 3第6版。你能推薦別的/更好的嗎? – user2092119

+1

如果你是關於這個問題本身,這是最接近我的參考:https://docs.jboss.org/jbossaop/docs/2.0.0.GA/docs/aspect-framework/reference/en/ HTML/reflection.html。關於其他的參考資料,你可以得到很好的答案:-)。 –