dwr.xml:
<dwr>
<allow>
<create javascript="UserService" creator="spring" >
<param name="beanName" value="userService"></param>
</create>
<!--调用UserService中的方法时将被DWRFilter拦截-->
<filter class="com.test.filter.DWRFilter"></filter>
<convert match="com.test.bean.User" converter="bean"></convert>
<!-调用UserService中的方法返回空对象时,让Dwr报错-->
<convert match="java.lang.NullPointerException" converter="exception"></convert>
</allow>
</dwr>
类DWRFilter代码如下:
import java.lang.reflect.Method;
import org.directwebremoting.AjaxFilter;
import org.directwebremoting.AjaxFilterChain;
import org.directwebremoting.util.Logger;
public class DWRFilter implements AjaxFilter {
public Object doFilter(Object object, Method method, Object[] arr,
AjaxFilterChain chain) throws Exception {
//System.out.println("拦截目标方法:"+method.getName());
log.debug("拦截目标方法:"+method.getName());
Object obj=chain.doFilter(object, method, arr);
//System.out.println("目标方法"+method.getName()+"执行结束");
log.debug("目标方法"+method.getName()+"执行结束");
return obj;
}
private static final Logger log=Logger.getLogger(DWRFilter.class);
}
下面测试Dwr的异常处理:
UserService中有如下方法:
public List testException(List list)
{
System.out.println("测试EXCEPTION");
try {
list.get(0);
} catch (Exception e) {
throw new NullPointerException("空指针异常");
}
return list;
}
JavaScript里通过dwr.xml配置的UserService调用此方法,如果返回对象为null,则Dwr报空指针异常错误:
var list=new Array('abc');
UserService.testException(list,{
callback:function(data){alert("正常:"+data[0])},
exceptionHandler:function(message){alert("异常:"+message)}
})