CXF是一个不错的开源的WS框架支持多种WS协议其中包括对附件上传的协议MTOM下文以一个例子来说明如何用CXF和MTOM来
实现上传一个WORD的文件到服务端
首先是服务端WS的实现我们编写一个POJO来处理一个待上传的简历
Resumejava
import javaxactivationDataHandler;
public class Resume
{
private String candidateName;
private String resumeFileType;
private DataHandler resume;
这里注意使用DataHandler来处理待上传的简历WORD文件
接口ResumeUploadServicejava
import javaxjwsWebParam;
import javaxjwsWebService;
import comtheadtoResume;
@WebService
public interface ResumeUploadService {
void uploadResume(@WebParam(name=resume) Resume resume);
}
这里使用了jaxws规范的注释去实现
实现类
import javaioFile;
import javaioFileOutputStream;
import javaioIOException;
import javaioInputStream;
import javaioOutputStream;
import javaxactivationDataHandler;
import javaxjwsWebService;
import comtheadtoResume;
@WebService(endpointInterface = comtheaserviceResumeUploadService
serviceName = ResumeService)
public class ResumeUploadServiceImpl implements ResumeUploadService {
public void uploadResume(Resume resume) {
DataHandler handler = resumegetResume();
try {
InputStream is = handlergetInputStream();
OutputStream os = new FileOutputStream(new File(c:\\
+ resumegetCandidateName() ++
resumegetResumeFileType()));
byte[] b = new byte[];
int bytesRead = ;
while ((bytesRead = isread(b)) != ) {
oswrite(b bytesRead);
}
osflush();
osclose();
isclose();
} catch (IOException e) {
eprintStackTrace();
}
}
}
然后在src目录下建立cxfxml做为服务端的配置文件
<beans xmlns=
xmlns:xsi=instance
xmlns:jaxws=
xsi:schemaLocation=
beansxsd
>
<import resource=classpath:METAINF/cxf/cxfxml />
<import resource=classpath:METAINF/cxf/cxfextensionsoapxml/>
<import resource=classpath:METAINF/cxf/cxfservletxml />
<jaxws:endpoint id=uploadresume
implementor=comtheaserviceResumeUploadServiceImpl
address=/UploadResumeWS>
<jaxws:properties>
<entry key=mtomenabled value=true/>
</jaxws:properties>
</jaxws:endpoint>
</beans>
这里注意使用了 <entry key=mtomenabled value=true/>设置使用MTOM附件
接下来设计客户端
作为客户端必须首先有Resume的POJO类以及还有服务端的接口ResumeUploadService设计的Client如下
public static void main(String args[]) throws Exception {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factorygetInInterceptors()add(new LoggingInInterceptor());
factorygetOutInterceptors()add(new LoggingOutInterceptor());
factorysetServiceClass(ResumeUploadServiceclass);
factorysetAddress
(//localhost:/CxfUploadService/services/UploadResumeWS);
ResumeUploadService client = (ResumeUploadService) factorycreate();
Resume resume=new Resume();
resumesetCandidateName(KarthikeyanC);
resumesetResumeFileType(doc);
DataSource source = new FileDataSource(new File(d:\\uploaddoc));
resumesetResume(new DataHandler(source));
clientuploadResume(resume);
Systemexit();
}
注意这里由于使用了JaxWsProxyFactoryBean并在程序中设定了对WS的各类指定所以不用再写客户端的WS文件了