技术开发 频道

WebService开发常见问题

  问题三:循环引用

  还是先来看一个例子。下面是WebService的接口:

1 @WebService
2     public interface IHello {
3     
4         @WebMethod
5         public String sayHello(Teacher teacher);
6     
7     }
8     
9     public class Teacher {
10         private Student[] students;
11         
12         //getters and setters
13         ...
14     }
15     
16     public class Student {
17         private Teacher teacher;
18         
19         //getters and setters
20         ...
21     }

  请注意,Teacher和Student是一对多的“双向”关系。在这种情况下,我们可以想一下如何将一个Teacher对象转换成一段XML?

  您可能想到下面的答案:

1 <teacher>
2         <students>
3             <teacher>
4                 <students>
5                     <teacher>
6                         <students>
7                             ...
8                         </students>
9                         ...
10                     </teacher>
11                 </students>
12                 ...
13             </teacher>
14         </students>
15         
16         <students>
17             ...
18         </students>
19         ...
20     </teacher>

  看到了吧,XML竟然也会进入“死循环”。问题的根源在于对象之间的循环引用。这种问题通常在客户端发送WebService请求之前就会抛出异常,因为无法将这个对象转换为可传输的XML。

2
相关文章