首页 > struts2 拦截器内 invoke 方法返回空

struts2 拦截器内 invoke 方法返回空

我的 struts2 拦截器内有以下代码

@Override
public String intercept(ActionInvocation ai) throws Exception {
    Object object = ai.getAction();
    Class<? extends Object> clazz = ai.getAction().getClass();
    Field[] fields = clazz.getDeclaredFields();

    try {
        for(Field field : fields) {
            PropertyDescriptor pd = null;
            try {
                pd = new PropertyDescriptor(field.getName(), clazz);  
            } catch (Exception e) {
                continue;
            }
                
            Method getMethod = pd.getReadMethod();     
            Method setMethod = pd.getWriteMethod();    
                
            Object o = getMethod.invoke(object); 
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}    

但是这句 Object o = getMethod.invoke(object); 里的 o 一直都是 null,这是为什么?


你要获取的目标字段在程序逻辑上是 action执行完之后得到的,还是只要有action对象才能获取?

如果是前置,你需要在拦截器里完成调用链的执行:

String result = ai.invoke();
Object object = ai.getAction();
Class<? extends Object> clazz = ai.getAction().getClass();
Field[] fields = clazz.getDeclaredFields();

try {
    for(Field field : fields) {
        PropertyDescriptor pd = null;
        try {
            pd = new PropertyDescriptor(field.getName(), clazz);  
        } catch (Exception e) {
            continue;
        }
            
        Method getMethod = pd.getReadMethod();     
        Method setMethod = pd.getWriteMethod();    
            
        Object o = getMethod.invoke(object); 
    }
} catch (Exception e) {
    e.printStackTrace();
}
return result;
【热门文章】
【热门文章】