2015-08-27 263 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。关于其他的参考资料,你可以得到很好的答案:-)。 –