在webservice中服务器抛出异常怎么能让客户端看到呢,可以自定义一个异常,继承
RemoteException,因为异常的传递实际上也相当于一个pojo对象,所以我们必须在服务器端进行序列化,在客户端进行反序列化,具体例子如下:
编写服务类:
package cn.com.test.ce.webservice;
import cn.com.test.ce.exception.TestException;
import cn.com.test.ce.pojo.Person;
public class Service
{
public Person getPerson(int i) throws TestException
{
Person person = new Person();
person.setId(1);
person.setName("张三");
if(i==1){
throw new TestException("测试一个异常");
}
return person;
}
}
编写异常类:
package cn.com.test.ce.exception;
import java.rmi.RemoteException;
public class TestException extends RemoteException{
public TestException(String s) {
super(s);
}
}
POJO类(可根据需要决定是否编写):
package cn.com.test.ce.pojo;
public class Person {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
编写客户端:
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.com.test.webservice;
import java.net.URL;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.utils.Options;
import cn.com.test.ce.pojo.Person;
import javax.xml.namespace.QName;
public class Client
{
public static void main(String [] args)
{
try {
//创建服务对象
Service service = new Service();
//通过服务对象创建调用对象
Call call=(Call)service.createCall();
String url = "http://localhost:8080/MyAxisExceptionWebService/services/MyService";
//设置调用的目标终端地址
call.setTargetEndpointAddress(new URL(url));
//设置对象的操作名称
call.setOperationName("getPerson");
//限定名必须与服务器端注册的保持一致
QName qn = new QName( "urn:Service", "Person" );
QName qn1 = new QName( "urn:exception:test", "TestException" );
//客户端反序列化,即把xml转化成java pojo对象
call.registerTypeMapping(Person.class, qn,
new org.apache.axis.encoding.ser.BeanSerializerFactory(Person.class, qn),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(Person.class, qn));
call.registerTypeMapping(Person.class, qn,
new org.apache.axis.encoding.ser.BeanSerializerFactory(Person.class, qn1),
new org.apache.axis.encoding.ser.BeanDeserializerFactory(Person.class, qn1));
// call.setOperationName( new QName("LogTestService", "testMethod") );
Person res = (Person) call.invoke( new Object[] {1} );
System.out.println( res );
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
具体发布步骤与访问方式不多说,请看前面简单的例子有详细描述,得到最后的结果
cn.com.test.ce.exception.TestException: 测试一个异常
则成功