如何把Soap Message装成一个String面向对象封装

SOAPMessage (Java Platform SE 7 )
JavaScript is disabled on your browser.
Class SOAPMessage
javax.xml.soap.SOAPMessage
public abstract class SOAPMessage
The root class for all SOAP messages. As transmitted on the "wire", a SOAP
message is an XML document or a MIME message whose first body part is an
XML/SOAP document.
A SOAPMessage object consists of a SOAP part and optionally
one or more attachment parts. The SOAP part for a SOAPMessage
object is a SOAPPart object, which contains information used
for message routing and identification, and which can contain
application-specific content. All data in the SOAP Part of a message must be
in XML format.
A new SOAPMessage object contains the following by default:
A SOAPPart object
A SOAPEnvelope object
A SOAPBody object
A SOAPHeader object
The SOAP part of a message can be retrieved by calling the method SOAPMessage.getSOAPPart().
The SOAPEnvelope object is retrieved from the SOAPPart
object, and the SOAPEnvelope object is used to retrieve the
SOAPBody and SOAPHeader objects.
SOAPPart sp = message.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
SOAPHeader sh = se.getHeader();
In addition to the mandatory SOAPPart object, a SOAPMessage
object may contain zero or more AttachmentPart objects, each
of which contains application-specific data. The SOAPMessage
interface provides methods for creating AttachmentPart
objects and also for adding them to a SOAPMessage object. A
party that has received a SOAPMessage object can examine its
contents by retrieving individual attachment parts.
Unlike the rest of a SOAP message, an attachment is not required to be in
XML format and can therefore be anything from simple text to an image file.
Consequently, any message content that is not in XML format must be in an
AttachmentPart object.
A MessageFactory object may create SOAPMessage
objects with behavior that is specialized to a particular implementation or
application of SAAJ. For instance, a MessageFactory object
may produce SOAPMessage objects that conform to a particular
Profile such as ebXML. In this case a MessageFactory object
might produce SOAPMessage objects that are initialized with
ebXML headers.
In order to ensure backward source compatibility, methods that are added to
this class after version 1.1 of the SAAJ specification are all concrete
instead of abstract and they all have default implementations. Unless
otherwise noted in the JavaDocs for those methods the default
implementations simply throw an UnsupportedOperationException
and the SAAJ implementation code must override them with methods that
provide the specified behavior. Legacy client code does not have this
restriction, however, so long as there is no claim made that it conforms to
some later version of the specification than it was originally written for.
A legacy class that extends the SOAPMessage class can be compiled and/or run
against succeeding versions of the SAAJ API without modification. If such a
class was correctly implemented then it will continue to behave correctly
relative to the version of the specification against which it was written.
See Also:,
Field Summary
Modifier and Type
Field and Description
Specifies the character type encoding for the SOAP Message.
Specifies whether the SOAP Message will contain an XML declaration when
it is sent.
Constructor Summary
Constructors&
Constructor and Description
Method Summary
Modifier and Type
Method and Description
abstract void
(&AttachmentPart)
Adds the given AttachmentPart object to this SOAPMessage
abstract int
Gets a count of the number of attachments in this message.
Creates a new empty AttachmentPart object.
(&dataHandler)
Creates an AttachmentPart object and populates it using
the given DataHandler object.
(&content,
&contentType)
Creates an AttachmentPart object and populates it with
the specified data of the specified content type.
(&element)
Returns an AttachmentPart object that is associated with an
attachment that is referenced by this SOAPElement or
null if no such attachment exists.
Retrieves all the AttachmentPart objects that are part of
this SOAPMessage object.
(&headers)
Retrieves all the AttachmentPart objects that have header
entries that match the specified headers.
Retrieves a description of this SOAPMessage object's
Returns all the transport-specific MIME headers for this SOAPMessage
object in a transport-independent fashion.
(&property)
Retrieves value of the specified property.
Gets the SOAP Body contained in this SOAPMessage object.
Gets the SOAP Header contained in this SOAPMessage
Gets the SOAP part of this SOAPMessage object.
abstract void
Removes all AttachmentPart objects that have been added
to this SOAPMessage object.
abstract void
(&headers)
Removes all the AttachmentPart objects that have header
entries that match the specified headers.
abstract void
Updates this SOAPMessage object with all the changes that
have been made to it.
abstract boolean
Indicates whether this SOAPMessage object needs to have
the method saveChanges called on it.
abstract void
(&description)
Sets the description of this SOAPMessage object's
content with the given description.
(&property,
Associates the specified value with the specified property.
abstract void
Writes this SOAPMessage object to the given output
Methods inherited from class&java.lang.
, , , , , , , , , ,
Field Detail
CHARACTER_SET_ENCODING
public static final& CHARACTER_SET_ENCODING
Specifies the character type encoding for the SOAP Message. Valid values
include "utf-8" and "utf-16". See vendor documentation for additional
supported values. The default is "utf-8".
See Also:,
WRITE_XML_DECLARATION
public static final& WRITE_XML_DECLARATION
Specifies whether the SOAP Message will contain an XML declaration when
it is sent. The only valid values are "true" and "false". The default is
See Also:,
Constructor Detail
SOAPMessage
public&SOAPMessage()
Method Detail
setContentDescription
public abstract&void&setContentDescription(&description)
Sets the description of this SOAPMessage object's
content with the given description.
Parameters:description - a String describing the content of this
messageSee Also:
getContentDescription
public abstract&&getContentDescription()
Retrieves a description of this SOAPMessage object's
Returns:a String describing the content of this
message or null if no description has been setSee Also:
getSOAPPart
public abstract&&getSOAPPart()
Gets the SOAP part of this SOAPMessage object.
SOAPMessage object contains one or more attachments, the
SOAP Part must be the first MIME body part in the message.
Returns:the SOAPPart object for this SOAPMessage
getSOAPBody
public&&getSOAPBody()
Gets the SOAP Body contained in this SOAPMessage object.
Returns:the SOAPBody object contained by this SOAPMessage
- if the SOAP Body does not exist or cannot be retrievedSince:
getSOAPHeader
public&&getSOAPHeader()
Gets the SOAP Header contained in this SOAPMessage
Returns:the SOAPHeader object contained by this SOAPMessage
- if the SOAP Header does not exist or cannot be retrievedSince:
removeAllAttachments
public abstract&void&removeAllAttachments()
Removes all AttachmentPart objects that have been added
to this SOAPMessage object.
This method does not touch the SOAP part.
countAttachments
public abstract&int&countAttachments()
Gets a count of the number of attachments in this message. This count
does not include the SOAP part.
Returns:the number of AttachmentPart objects that are
part of this SOAPMessage object
getAttachments
public abstract&&getAttachments()
Retrieves all the AttachmentPart objects that are part of
this SOAPMessage object.
Returns:an iterator over all the attachments in this message
getAttachments
public abstract&&getAttachments(&headers)
Retrieves all the AttachmentPart objects that have header
entries that match the specified headers. Note that a returned
attachment could have headers in addition to those specified.
Parameters:headers - a MimeHeaders object containing the MIME
headers for which to search
Returns:an iterator over all attachments that have a header that matches
one of the given headers
removeAttachments
public abstract&void&removeAttachments(&headers)
Removes all the AttachmentPart objects that have header
entries that match the specified headers. Note that the removed
attachment could have headers in addition to those specified.
Parameters:headers - a MimeHeaders object containing the MIME
headers for which to searchSince:
getAttachment
public abstract&&getAttachment(&element)
Returns an AttachmentPart object that is associated with an
attachment that is referenced by this SOAPElement or
null if no such attachment exists. References can be made
via an href attribute as described in
or via a single Text child node containing a URI as
described in the WS-I Attachments Profile 1.0 for elements of schema
These two mechanisms must be supported.
The support for references via href attribute also implies that
this method should also be supported on an element that is an
xop:Include element (
other reference mechanisms may be supported by individual
implementations of this standard. Contact your vendor for details.
Parameters:element - The SOAPElement containing the reference to an Attachment
Returns:the referenced AttachmentPart or null if no such
AttachmentPart exists or no reference can be
found in this SOAPElement.
- if there is an error in the attempt to access the
attachmentSince:
addAttachmentPart
public abstract&void&addAttachmentPart(&AttachmentPart)
Adds the given AttachmentPart object to this SOAPMessage
object. An AttachmentPart object must be created before
it can be added to a message.
Parameters:AttachmentPart - an AttachmentPart object that is to become part
of this SOAPMessage object
createAttachmentPart
public abstract&&createAttachmentPart()
Creates a new empty AttachmentPart object. Note that the
method addAttachmentPart must be called with this new
AttachmentPart object as the parameter in order for it to
become an attachment to this SOAPMessage object.
Returns:a new AttachmentPart object that can be populated
and added to this SOAPMessage object
createAttachmentPart
public&&createAttachmentPart(&dataHandler)
Creates an AttachmentPart object and populates it using
the given DataHandler object.
Parameters:dataHandler - the javax.activation.DataHandler object that
will generate the content for this SOAPMessage
Returns:a new AttachmentPart object that contains data
generated by the given DataHandler object
- if there was a problem with the specified DataHandler
objectSee Also:,
getMimeHeaders
public abstract&&getMimeHeaders()
Returns all the transport-specific MIME headers for this SOAPMessage
object in a transport-independent fashion.
Returns:a MimeHeaders object containing the MimeHeader
createAttachmentPart
public&&createAttachmentPart(&content,
&contentType)
Creates an AttachmentPart object and populates it with
the specified data of the specified content type. The type of the
Object should correspond to the value given for the
Content-Type.
Parameters:content - an Object containing the content for the
AttachmentPart object to be createdcontentType - a String object giving
examples are "text/xml", "text/plain", and "image/jpeg"
Returns:a new AttachmentPart object that contains the
given data
- may be thrown if the contentType does not match the type
of the content object, or if there was no
DataContentHandler object for the given
content objectSee Also:,
saveChanges
public abstract&void&saveChanges()
Updates this SOAPMessage object with all the changes that
have been made to it. This method is called automatically when
called. However, if
changes are made to a message that was received or to one that has
already been sent, the method saveChanges needs to be
called explicitly in order to save the changes. The method saveChanges
also generates any changes that can be read back (for example, a
MessageId in profiles that support a message id). All MIME headers in a
message that is created for sending purposes are guaranteed to have
valid values only after saveChanges has been called.
In addition, this method marks the point at which the data from all
constituent AttachmentPart objects are pulled into the
SOAPException - if there was a problem saving
changes to this message.
saveRequired
public abstract&boolean&saveRequired()
Indicates whether this SOAPMessage object needs to have
the method saveChanges called on it.
Returns:true if saveChanges needs to be
false otherwise.
public abstract&void&writeTo(&out)
Writes this SOAPMessage object to the given output
stream. The externalization format is as defined by the SOAP 1.1 with
Attachments specification.
If there are no attachments, just an XML stream is written out. For
those messages that have attachments, writeTo writes a
MIME-encoded byte stream.
Note that this method does not write the transport-specific MIME Headers
of the Message
Parameters:out - the OutputStream object to which this SOAPMessage
object will be written
- if an I/O error occurs
- if there was a problem in externalizing this SOAP message
setProperty
public&void&setProperty(&property,
Associates the specified value with the specified property. If there was
already a value associated with this property, the old value is
The valid property names include
. All of these standard SAAJ
properties are prefixed by "javax.xml.soap". Vendors may also add
implementation specific properties. These properties must be prefixed
with package names that are unique to the vendor.
Setting the property WRITE_XML_DECLARATION to "true"
will cause an XML Declaration to be written out at the start of the SOAP
message. The default value of "false" suppresses this declaration.
The property CHARACTER_SET_ENCODING defaults to the value
"utf-8" which causes the SOAP message to be encoded using
UTF-8. Setting CHARACTER_SET_ENCODING to "utf-16"
causes the SOAP message to be encoded using UTF-16.
Some implementations may allow encodings in addition to UTF-8 and
UTF-16. Refer to your vendor's documentation for details.
Parameters:property - the property with which the specified value is to be
associated.value - the value to be associated with the specified property
- if the property name is not recognized.Since:
getProperty
public&&getProperty(&property)
Retrieves value of the specified property.
Parameters:property - the name of the property to retrieve
Returns:the value associated with the named property or null
if no such property exists.
- if the property name is not recognized.Since:
For further API reference and developer documentation, see . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
© , Oracle and/or its affiliates.
All rights reserved. Use is subject to . Also see the .
Scripting on this page tracks web page traffic, but does not change the content in any way.2016年1月 Java大版内专家分月排行榜第二2015年12月 Java大版内专家分月排行榜第二2015年8月 Java大版内专家分月排行榜第二2015年3月 Java大版内专家分月排行榜第二2015年1月 Java大版内专家分月排行榜第二2014年12月 Java大版内专家分月排行榜第二2014年11月 Java大版内专家分月排行榜第二2014年6月 Java大版内专家分月排行榜第二2014年4月 Java大版内专家分月排行榜第二2014年1月 Java大版内专家分月排行榜第二2013年11月 Java大版内专家分月排行榜第二
2015年9月 Java大版内专家分月排行榜第三2015年6月 Java大版内专家分月排行榜第三2015年5月 Java大版内专家分月排行榜第三2015年2月 Java大版内专家分月排行榜第三2014年3月 Java大版内专家分月排行榜第三2013年12月 Java大版内专家分月排行榜第三
本帖子已过去太久远了,不再提供回复功能。人气:157706
访问用户量:130
笔记经验:445
总积分:2667
级别:VIP1
搜索本笔记
ta的交流分类
ta的全部笔记
浏览(17798)|(0)
&&交流分类:|笔记分类:
一 soap消息的格式
二 soap消息的创建
java代码:
//1、创建消息工厂
MessageFactory factory = MessageFactory.newInstance();
//2、根据消息工厂创建SoapMessage
SOAPMessage message = factory.createMessage();
//3、创建SOAPPart
SOAPPart part = message.getSOAPPart();
//4、获取SOAPENvelope
SOAPEnvelope envelope = part.getEnvelope();
//5、可以通过SoapEnvelope有效的获取相应的Body和Header等信息
SOAPBody body = envelope.getBody();
//6、根据Qname创建相应的节点(QName就是一个带有命名空间的节点)
//&ns:add xmlns=&http://java./webservice&/&
QName qname = new QName(&http://java./webservice&, &add&,&ns&);
//如果使用以下方式进行设置,会见&&转换为&和&gt
//body.addBodyElement(qname).setValue(&&a&1&/a&&b&2&/b&&);
SOAPBodyElement ele = body.addBodyElement(qname);
ele.addChildElement(&a&).setValue(&22&); ele.addChildElement(&b&).setValue(&33&);
//打印消息信息
message.writeTo(System.out);
三 消息传递
java代码:
//1、创建服务(Service)
URL url = new URL(wsdlUrl);
QName sname = new QName(ns,&MyServiceImplService&);
Service service = Service.create(url,sname);
//2、创建Dispatch
Dispatch&SOAPMessage& dispatch = service.createDispatch(new QName(ns,&MyServiceImplPort&),SOAPMessage.class,Service.Mode.MESSAGE);
//3、创建SOAPMessage
SOAPMessage msg = MessageFactory.newInstance().createMessage();
SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
SOAPBody body = envelope.getBody();
//4、创建QName来指定消息中传递数据
QName ename = new QName(ns,&add&,&nn&);//&nn:add xmlns=&xx&/&
SOAPBodyElement ele = body.addBodyElement(ename);
ele.addChildElement(&a&).setValue(&22&);
ele.addChildElement(&b&).setValue(&33&);
msg.writeTo(System.out);
System.out.println(&\n invoking.....&);
//5、通过Dispatch传递消息,会返回响应消息
SOAPMessage response = dispatch.invoke(msg);
response.writeTo(System.out);
System.out.println();
//6、响应消息处理,将响应的消息转换为dom对象
Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
String str = doc.getElementsByTagName(&addResult&).item(0).getTextContent();
System.out.println(str);
相关笔记推荐
精品视频课程推荐
JavaScript的内置对象--Array、String、Date、Math等,可以通过DOM对象进行对象控制,创建控制菜单及复选框的控制,创建二级联动列表框及列表框选项的移动,JavaScript项目,创建基于JS的商品管理系统。
WebLogic基础知识:WebLogic基本概念、正确安装WebLogic、建域、应用部署于JDBC选择、对WebLogic的监控和日志查看、集群的高可用性;课程目标:彻底掌握WebLogic的基本概念,在理解基本概念的基础上做到正确的安装WebLogic,根据不同的需求创建域,合理选择应用部署和JDBC配置。熟练掌握WebLogic的console监控,了解各种性能和运行指标,以及对监控结果的分析,运用集群的高可用性,对集群架设。
本课程专注于数据结构和算法的内容,使用Java来进行代码示例,不空洞的讲解概念和理论,重点放在代码的实现和示例上。
从零开始、全面系统、成体系的讲解数据结构和基本算法,循序渐进的讲述构建软件系统所常见的数据结构和算法。
系统、完整的学习Spring Web MVC开发的知识。包括:Spring Web MVC入门;理解DispatcherServlet;注解式控制器开发详解;数据类型转换;数据格式化;数据验证; 拦截器;对Ajax的支持;文件上传下载;表单标签等内容;最后以一个综合的CRUD带翻页的应用示例来综合所学的知识
数据校验、Javascript模拟多线程、下拉列表联动、操作XML、AJAX结合JSON的操作、Json-lib的使用
浏览(17798)|(0)
&&交流分类:|笔记分类:
版权所有 Copyright(C) 私塾在线学习网JAX-WS:异步与soapheader加用户验证Handler机制
我的图书馆
JAX-WS:异步与soapheader加用户验证Handler机制
前面介绍了如何创建基于JAX-WS的webservice以及传递对象的一些相关内容,下面介绍下异步和Handler机制1、异步JAX-WS支持客户端的异步调用。在Server与普通的没多大区别,这里声明一个server服务:Java代码&&@WebService(serviceName&=&"asynJaxWsService",&endpointInterface&=&"org.ws.server.ws.chap3.AsynJaxWsService")&&public&class&AsynJaxWsServiceImpl&implements&AsynJaxWsService&{&&&&&&&&@WebMethod&&&&&&public&@WebResult&&&&&&Address&asynAddress(String&id)&{&&&&&&&&&&Address&address&=&new&Address();&&&&&&&&&&address.setCity("chengdu");&&&&&&&&&&address.setStreet("xxxx");&&&&&&&&&&try&{&&&&&&&&&&&&&&Thread.sleep(5000);&&&&&&&&&&}&catch&(InterruptedException&e)&{&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&}&&&&&&&&&&return&&&&&&&}&&&&}&&&在发布服务后,生产客户端代码需要指定jaxws/bind文件,对于异步的bing.xml如下:Xml代码&&&&&&&&&&&xmlns:xsd="http://www.w3.org/2001/XMLSchema"&&&&&&&xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"&&&&&&&wsdlLocation="http://localhost:8080/service/asynJaxWsService?wsdl"&&&&&&xmlns="/xml/ns/jaxws"&&&&&&&node="wsdl:definitions"&&&&&&&&&&true&&&&&&&&&&然后生产客户端代码命令:Java代码&&wsimport&-p&org.sample.ws.client.ws.chap3&-keep&http:&&&在生产的客户端代码中提供了两种方式来异步调用:Java代码&&public&Response&AsynAddressResponse&&asynAddressAsync(&&&&&&&&&&@WebParam(name&=&"arg0",&targetNamespace&=&"")&&&&&&&&&&String&arg0);&&&&public&Future&?&&asynAddressAsync(&&&&&&&&&&@WebParam(name&=&"arg0",&targetNamespace&=&"")&&&&&&&&&&String&arg0,&&&&&&&&&&@WebParam(name&=&"asyncHandler",&targetNamespace&=&"")&&&&&&&&&&AsyncHandler&AsynAddressResponse&&asyncHandler);&&可通过如下方式调用:Java代码&&AsynJaxWsService&jaxWs&=&new&AsynJaxWsService_Service().getAsynJaxWsServiceImplPort();&&&&jaxWs.asynAddressAsync("123",&new&AsyncHandler&AsynAddressResponse&()&{&&&&&&&&public&void&handleResponse(Response&AsynAddressResponse&&res)&{&&&&&&&&&&try&{&&&&&&&&&&&&&&AsynAddressResponse&response&=&res.get();&&&&&&&&&&&&&&Address&address&=&response.getReturn();&&&&&&&&&&&&&&System.out.println(ToStringBuilder.reflectionToString(address,&ToStringStyle.SHORT_PREFIX_STYLE));&&&&&&&&&&}&catch&(InterruptedException&e)&{&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&}&catch&(ExecutionException&e)&{&&&&&&&&&&&&&&e.printStackTrace();&&&&&&&&&&}&&&&&&}&&});&&&&Response&AsynAddressResponse&&response&=&jaxWs.asynAddressAsync("123");&&while&(!response.isDone())&{&&&&&&System.out.println("not&ending....");&&}&&AsynAddressResponse&addressResponse&=&response.get();&&Address&address&=&addressResponse.getReturn();&&System.out.println(ToStringBuilder.reflectionToString(address,&ToStringStyle.SHORT_PREFIX_STYLE));&&&2、Handler机制Handler机制(Filter、Interceptor)是很多框架必不可少的东西,甚至是构建在这个概念之上。在JAX-WS中提供了两种Handler机制:Logical Handlers and Protocol Handlers,简单地说前者处理业务上的后者处理访问等header层,更多信息见。我们这里要实现的一个简单授权访问的例子,就是基于ProtocolHandler(SOAPHandler),通过header中创建相应的节点来判断用户名或密码达到校验的目录。首先来看看server端代码,自定义AuthHandler需要实现SOAPHandler:Java代码&&public&class&AuthHandler&implements&SOAPHandler&SOAPMessageContext&&{&&&&&&&&public&boolean&handleMessage(SOAPMessageContext&context)&{&&&&&&&&&&boolean&isRequest&=&(Boolean)&context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);&&&&&&&&&&&&if&(!isRequest)&{&&&&&&&&&&&&&&&&try&{&&&&&&&&&&&&&&&&&&SOAPMessage&soapMsg&=&context.getMessage();&&&&&&&&&&&&&&&&&&SOAPEnvelope&soapEnv&=&soapMsg.getSOAPPart().getEnvelope();&&&&&&&&&&&&&&&&&&SOAPHeader&soapHeader&=&soapEnv.getHeader();&&&&&&&&&&&&&&&&&&&&if&(soapHeader&==&null)&{&&&&&&&&&&&&&&&&&&&&&&soapHeader&=&soapEnv.addHeader();&&&&&&&&&&&&&&&&&&&&&&generateSOAPErrMessage(soapMsg,&"No&SOAP&header.");&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&Iterator&?&&it&=&soapHeader.extractHeaderElements(SOAPConstants.URI_SOAP_ACTOR_NEXT);&&&&&&&&&&&&&&&&&&&&if&(it&==&null&||&!it.hasNext())&{&&&&&&&&&&&&&&&&&&&&&&generateSOAPErrMessage(soapMsg,&"No&header&block&for&next&actor.");&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&while&(it.hasNext())&{&&&&&&&&&&&&&&&&&&&&&&Node&node&=&(Node)&it.next();&&&&&&&&&&&&&&&&&&&&&&if&("auth".equals(node.getNodeName())&&&&"aaaaaaaaaaaa".equals(node.getValue()))&&&&&&&&&&&&&&&&&&&&&&&&&&return&true;&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&generateSOAPErrMessage(soapMsg,&"invalid&user");&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&soapMsg.writeTo(System.out);&&&&&&&&&&&&&&&&}&catch&(SOAPException&e)&{&&&&&&&&&&&&&&&&&&System.err.println(e);&&&&&&&&&&&&&&}&catch&(IOException&e)&{&&&&&&&&&&&&&&&&&&System.err.println(e);&&&&&&&&&&&&&&}&&&&&&&&&&&&}&&&&&&&&&&return&true;&&&&&&&&}&&&&&&&&public&boolean&handleFault(SOAPMessageContext&context)&{&&&&&&&&&&return&true;&&&&&&}&&&&&&&&public&void&close(MessageContext&context)&{&&&&&&&&}&&&&&&&&public&Set&QName&&getHeaders()&{&&&&&&&&&&return&null;&&&&&&}&&&&&&&&private&void&generateSOAPErrMessage(SOAPMessage&msg,&String&reason)&{&&&&&&&&&&try&{&&&&&&&&&&&&&&SOAPBody&soapBody&=&msg.getSOAPPart().getEnvelope().getBody();&&&&&&&&&&&&&&SOAPFault&soapFault&=&soapBody.addFault();&&&&&&&&&&&&&&soapFault.setFaultString(reason);&&&&&&&&&&&&&&throw&new&SOAPFaultException(soapFault);&&&&&&&&&&}&catch&(SOAPException&e)&{&&&&&&&&&&}&&&&&&}&&&&}&&&在handler-chain.xml中声明Xml代码&&&version="1.0"&encoding="UTF-8"&standalone="yes"&&&&&&&&&xmlns:javaee="/xml/ns/javaee"&&&&&&&xmlns:xsd="http://www.w3.org/2001/XMLSchema"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&org.ws.server.ws.chap7.AuthHandler&&&&&&&&&&&&&&&&&&&&server接口没多大变化,只需要添加@HandlerChain(file = "handler-chain.xml")指定配置文件Java代码&&@WebService&&@HandlerChain(file&=&"handler-chain.xml")&&public&class&JaxWsHandlerServiceImpl&implements&JaxWsHandlerService&{&&&&&&&&@WebMethod&&&&&&public&String&sayHello()&{&&&&&&&&&&return&"Hello,&Service";&&&&&&}&&&&}&&&发布即可完成server端的配置。接下来看看客户端,通过命令生成客户端代码后,同样需要编写handler,需要处理就是在SOAP消息的Header中添加Node,起name和value分别对应server端的配置:Java代码&&public&class&JaxWsClientHandler&implements&SOAPHandler&SOAPMessageContext&&{&&&&&&&&public&boolean&handleMessage(SOAPMessageContext&context)&{&&&&&&&&&&System.out.println("Client&:&handleMessage()......");&&&&&&&&&&&&Boolean&isRequest&=&(Boolean)&context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);&&&&&&&&&&&&&&&&&&&&&&if&(isRequest)&{&&&&&&&&&&&&&&&&try&{&&&&&&&&&&&&&&&&&&SOAPMessage&soapMsg&=&context.getMessage();&&&&&&&&&&&&&&&&&&SOAPEnvelope&soapEnv&=&soapMsg.getSOAPPart().getEnvelope();&&&&&&&&&&&&&&&&&&SOAPHeader&soapHeader&=&soapEnv.getHeader();&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&if&(soapHeader&==&null)&{&&&&&&&&&&&&&&&&&&&&&&soapHeader&=&soapEnv.addHeader();&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&QName&qname&=&new&QName("/",&"auth");&&&&&&&&&&&&&&&&&&SOAPHeaderElement&soapHeaderElement&=&soapHeader.addHeaderElement(qname);&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);&&&&&&&&&&&&&&&&&&soapHeaderElement.addTextNode("aaaaaaaaaaaa");&&&&&&&&&&&&&&&&&&soapMsg.saveChanges();&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&soapMsg.writeTo(System.out);&&&&&&&&&&&&&&&&}&catch&(SOAPException&e)&{&&&&&&&&&&&&&&&&&&System.err.println(e);&&&&&&&&&&&&&&}&catch&(IOException&e)&{&&&&&&&&&&&&&&&&&&System.err.println(e);&&&&&&&&&&&&&&}&&&&&&&&&&&&}&&&&&&&&&&return&true;&&&&&&}&&&&&&&&public&boolean&handleFault(SOAPMessageContext&context)&{&&&&&&&&&&return&true;&&&&&&}&&&&&&&&public&void&close(MessageContext&context)&{&&&&&&&&}&&&&&&&&public&Set&QName&&getHeaders()&{&&&&&&&&&&return&null;&&&&&&}&&&&}&&其他工作与服务端一样,编写handler-chain.xmlXml代码&&&version="1.0"&encoding="UTF-8"&standalone="yes"&&&&&&&&&xmlns:javaee="/xml/ns/javaee"&&&&&&&xmlns:xsd="http://www.w3.org/2001/XMLSchema"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&org.sample.ws.client.ws.chap7.main.JaxWsClientHandler&&&&&&&&&&&&&&&&&&&&同时在生成的客户端代理类中需要加入该hander-chain,看起来是这样的:Java代码&&@WebServiceClient(name&=&"JaxWsHandlerServiceImplService",&targetNamespace&=&"http://impl.chap7.ws.server.ws.org/",&wsdlLocation&=&"http://localhost:8080/service/jaxWsAuthSrevice?wsdl")&&@HandlerChain(file&=&"handler-chain.xml")&&public&class&JaxWsHandlerServiceImplService&&&&&&extends&Service&&这样就完成了一个简单的实例,按照普通的调用即可:Java代码&&JaxWsHandlerServiceImpl&service&=&new&JaxWsHandlerServiceImplService().getJaxWsHandlerServiceImplPort();&&System.out.println(service.sayHello());&&如果没有auth节点或者value(密码)不对就会抛出异常如:Java代码&&at&com.sun.xml.internal.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:178)&&at&com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:111)&&at&com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)&&at&com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:78)&&at&com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:107)&&at&$Proxy29.sayHello(Unknown&Source)&&at&org.sample.ws.client.ws.chap7.main.JaxWsHandlerServiceMain.main(JaxWsHandlerServiceMain.java:15)&&&
发表评论:
TA的最新馆藏

我要回帖

更多关于 如何将对象封装成json 的文章

 

随机推荐