java拦截器不拦截

时间:2015-08-27 20:42:37

标签: java java-ee ejb interceptor

下面是一个简单的Web应用程序,配置为在glassfish4上运行的Rest服务。应用程序本身可以工作,可以访问单个资源。

拦截器不适用于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 个答案:

答案 0 :(得分:1)

免责声明:这是一个猜测,因为我没有找到任何关于此的支持文档,它也可能取决于服务器的/ JRE实现

它不起作用,因为使用java反射/内省技术调用@GET注释方法。这避免了框架拦截该调用,因为它直接在JRE中完成。

要证明这一点而不是调用&#34; pong&#34;直接在您尝试以下操作时:

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那样被截获。

我能想到的唯一可行的工作就是你已经做过的事情:在另一个没有注释的方法中提取逻辑。