CXF3.0.2+Spring3.2.14 WebService入门实例四

这次学习CXF WebService传输文件。CXF采用的是MTOM的机制进行文件传输。MTOM(Message Transmission Optimization Mechanism)消息优化传输机制。消息传输优化机制 (MTOM) 标准允许将消息中包含的大型数据元素外部化,并将其作为无任何特殊编码的二进制数据随消息一起传送。MTOM 消息会打包为多部分/相关 MIME 序列,放在SOAP 消息中一起传送。

但是在大量数据情况下,如果数据依然进行Base64编码,会带来33%的额外开销,这样的情况对于大量数据交换的情况是无法容忍的。MTOM 就是针对SOAP 消息传输的基础上提出的改进办法。对于大量数据的传递,不会进行进行Base64编码,而是直接以附件的二进制原始数据的形式封装在SOAP消息的 MIME 部分,进行传输。………此处略去1000字,自己百度补齐………

首先还是要介绍一下开发工具和开发环境,jdk1.6.0_43+Tomcat6.0.29+MyEclipse10.5,没有使用Maven进行管理!

继续学习达拉斯母牛的CXF实战之传输文件(六),

博客地址:http://blog.csdn.net/accountwcx/article/details/47165321

一、新建web工程,选择Java EE5.0

二、新建文件传输类CxfFileWrapper.java

package com.util;

import javax.activation.DataHandler;

import javax.xml.bind.annotation.XmlMimeType;

import javax.xml.bind.annotation.XmlType;

/**

* 类名: CxfFileWrapper.java

* 作者:张述飞

* 创建时间: 2016-1-7下午2:35:44

* 版本: V1.0

* 功能描述: CXF上传和下载文件对象包装类由于CXFDataHandler无法获取文件名和文件类型,需要在上传和下载时附带文件名

*/

@XmlType(name = "cxfFileWrapper")

public class CxfFileWrapper{

//文件名

private StringfileName;

//文件扩展名

private StringfileExtension;

//文件二进制数据

private DataHandlerfile;

public String getFileName() {

returnfileName;

}

public void setFileName(String fileName) {

this.fileName = fileName;

}

public String getFileExtension() {

returnfileExtension;

}

public void setFileExtension(String fileExtension) {

this.fileExtension = fileExtension;

}

//注解该字段为二进制流

@XmlMimeType("application/octet-stream")

public DataHandler getFile() {

returnfile;

}

public void setFile(DataHandler file) {

this.file = file;

}

}

三、新建接口类FileInterface.java

package com.util;

importjavax.jws.WebMethod;

importjavax.jws.WebParam;

importjavax.jws.WebService;

importjavax.xml.ws.soap.MTOM;

/**

* 类名:FileInterface.java

* 作者: 张述飞

* 创建时间: 2016-1-12上午8:24:05

* 版本: V1.0

* 功能描述:接口类

* 说明:@MTOM注解非常重要,如果不写,那么下载文件时会报内存溢出的错误!

2016-1-8 15:14:29org.apache.catalina.core.StandardWrapperValve invoke

严重: Servlet.service() for servlet CXFService threwexception

java.lang.OutOfMemoryError:Java heap space

at com.sun.xml.bind.v2.util.ByteArrayOutputStreamEx.readFrom(ByteArrayOutputStreamEx.java:75)

……………………………

*/

@WebService(name="fileInterface")

@MTOM

public interfaceFileInterface {

/**

* 文件上传

*@param file

*@return

*/

@WebMethod

public boolean upload(@WebParam(name ="file") CxfFileWrapper file);

/**

* 文件下载

*@return

*@throws Exception

*/

@WebMethod

public CxfFileWrapper download();

}

四、新建接口实现类FileInterfaceImpl.java

package com.util;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.jws.WebService;

@WebService(endpointInterface="com.util.FileInterface", portName="FileInterPort")

public class FileInterfaceImplimplements FileInterface {

public boolean upload(CxfFileWrapper file) {

boolean result =true;

OutputStream os = null;

InputStream is = null;

BufferedOutputStream bos = null;

try {

is = file.getFile().getInputStream();

/**

* 注必须先在D盘新建文件夹newFile

java.io.FileNotFoundException: d:\newFile\LoginDB.bak (系统找不到指定的路径。)

at java.io.FileOutputStream.open(Native Method)

at java.io.FileOutputStream.<init>(FileOutputStream.java:194)

*/

File dest = new File("d:\\newFile\\" + file.getFileName());

os = new FileOutputStream(dest);

bos = new BufferedOutputStream(os);

byte[] buffer =new byte[100000];

int len = 0;

while ((len = is.read(buffer)) != -1) {

bos.write(buffer, 0, len);

}

bos.flush();

} catch (IOException e) {

e.printStackTrace();

result = false;

} finally {

if (bos !=null) {

try {

bos.close();

} catch (IOException e) {

}

}

if (os !=null) {

try {

os.close();

} catch (IOException e) {

}

}

if (is !=null) {

try {

is.close();

} catch (IOException e) {

}

}

}

return result;

}

/**

* 说明:此处导出的数据库文件大约1.8G,但是没有找到从服务上下载文件的实例

*/

public CxfFileWrapper download() {

String filePath = "D:\\ERPDB\\LoginDB.bak";

CxfFileWrapper fileWrapper = new CxfFileWrapper();

fileWrapper.setFileName("LoginDB");

fileWrapper.setFileExtension("bak");

DataSource source = new FileDataSource(new File(filePath));

fileWrapper.setFile(new DataHandler(source));

return fileWrapper;

}

}

五、applicationContext.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"

xmlns:jaxws="http://cxf.apache.org/jaxws"

xsi:schemaLocation="

http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsd

http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsd

http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd

http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd

http://cxf.apache.org/transports/http/configurationhttp://cxf.apache.org/schemas/configuration/http-conf.xsd

http://cxf.apache.org/jaxwshttp://cxf.apache.org/schemas/jaxws.xsd">

<importresource="classpath:META-INF/cxf/cxf.xml"/>

<importresource="classpath:META-INF/cxf/cxf-servlet.xml"/>

<http-conf:destinationname="*.http-destination">

<http-conf:serverReceiveTimeout="90000"/>

</http-conf:destination>

<beanid="fileInterface"class="com.util.FileInterfaceImpl"/>

<jaxws:endpointid="myfile"implementor="#fileInterface"address="/upfile">

<jaxws:inInterceptors>

<beanclass="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>

</jaxws:inInterceptors>

<jaxws:outInterceptors>

<beanclass="org.apache.cxf.interceptor.LoggingOutInterceptor"></bean>

</jaxws:outInterceptors>

<jaxws:properties>

<!-- 开启MTOM-->

<entrykey="mtom_enabled"value="true"></entry>

</jaxws:properties>

</jaxws:endpoint>

<!--利用Spring调用-->

<beanid="client"class="com.util.FileInterface"factory-bean="clientFactory"factory-method="create"/>

<beanid="clientFactory"class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">

<propertyname="serviceClass"value="com.util.FileInterface"></property>

<propertyname="address"value="http://localhost:8080/WbFile/upfile"></property>

<propertyname="properties">

<map><entrykey="mtom-enable"value="true"></entry></map>

</property>

</bean>

</beans>

六、web.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<web-appversion="2.5"

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<display-name></display-name>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

classpath:applicationContext.xml

</param-value>

</context-param>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<!--Spring刷新Introspector防止内在泄露-->

<listener>

<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>

</listener>

<servlet>

<servlet-name>CXFService</servlet-name>

<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>CXFService</servlet-name>

<url-pattern>/*</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

七、需导入的jar包

aopalliance-1.0.jar

asm-3.3.1.jar

commons-logging-1.1.3.jar

cxf-core-3.0.7.jar

cxf-manifest.jar

cxf-rt-bindings-soap-3.0.7.jar

cxf-rt-databinding-jaxb-3.0.7.jar

cxf-rt-frontend-jaxws-3.0.7.jar

cxf-rt-frontend-simple-3.0.7.jar

cxf-rt-transports-http-3.0.7.jar

cxf-rt-transports-http-jetty-3.0.7.jar

cxf-rt-ws-addr-3.0.7.jar

cxf-rt-ws-policy-3.0.7.jar

cxf-rt-wsdl-3.0.7.jar

geronimo-javamail_1.4_spec-1.7.1.jar

geronimo-jaxws_2.2_spec-1.2.jar

jaxb-api-2.2.11.jar

jaxb-core-2.2.11.jar

jaxb-impl-2.2.11.jar

jetty-continuation-8.1.15.v20140411.jar

jetty-http-8.1.15.v20140411.jar

jetty-io-8.1.15.v20140411.jar

jetty-security-8.1.15.v20140411.jar

jetty-server-8.1.15.v20140411.jar

jetty-util-8.1.15.v20140411.jar

neethi-3.0.3.jar

servlet-api.jar

slf4j-api-1.7.9.jar

slf4j-jdk14-1.7.9.jar

spring-aop-3.2.14.RELEASE.jar

spring-beans-3.2.14.RELEASE.jar

spring-context-3.2.14.RELEASE.jar

spring-core-3.2.14.RELEASE.jar

spring-expression-3.2.14.RELEASE.jar

spring-web-3.2.14.RELEASE.jar

stax2-api-3.1.4.jar

woodstox-core-asl-4.4.1.jar

wsdl4j-1.6.3.jar

xmlschema-core-2.2.1.jar

八、新建测试类Client.java

package com.test;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URL;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import org.apache.cxf.interceptor.LoggingInInterceptor;

import org.apache.cxf.interceptor.LoggingOutInterceptor;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import com.util.CxfFileWrapper;

import com.util.FileInterface;

public class Client {

public void upload(){

JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

factory.setServiceClass(FileInterface.class);

factory.setAddress("http://localhost:8080/WbFile/upfile");

factory.getInInterceptors().add(new LoggingInInterceptor());

factory.getOutInterceptors().add(new LoggingOutInterceptor());

FileInterface fileinter = factory.create(FileInterface.class);

CxfFileWrapper fileWrapper = new CxfFileWrapper();

fileWrapper.setFileName("LoginDB.bak");

fileWrapper.setFileExtension("bak");

String filePath = "D:\\ERPDB\\LoginDB.bak";

DataSource source = new FileDataSource(new File(filePath));

fileWrapper.setFile(new DataHandler(source));

boolean success = fileinter.upload(fileWrapper);

System.out.println(success ?"上传成功!":"上传失败!");

}

/**

* 下载本地文件到C

*/

public void downFile1(){

JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

factory.setServiceClass(FileInterface.class);

factory.setAddress("http://localhost:8080/WbFile/upfile");

FileInterface fin = factory.create(FileInterface.class);

CxfFileWrapper xfw = fin.download();

OutputStream os = null;

InputStream is = null;

BufferedOutputStream bos = null;

try {

is = xfw.getFile().getInputStream();

File dest = new File("c:\\"+xfw.getFileName()+"."+xfw.getFileExtension());

os = new FileOutputStream(dest);

bos = new BufferedOutputStream(os);

byte[] buffer =new byte[100000];

int len = 0;

while ((len = is.read(buffer)) != -1) {

bos.write(buffer, 0, len);

}

bos.flush();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (bos !=null) {

try {

bos.close();

} catch (IOException e) {

}

}

if (os !=null) {

try {

os.close();

} catch (IOException e) {

}

}

if (is !=null) {

try {

is.close();

} catch (IOException e) {

}

}

}

}

/**

* 从服务器上下载文件到本地,需要在服务器安装tomcat

* 然后建立一个MyFile.xml文件,需要指向虚拟目录

*/

public void downFile2(){

OutputStream os = null;

InputStream is = null;

try {

String filePath = "http://172.16.0.2:8080/MyFile/2016010501.zip";

URL url = new URL(filePath);

is = url.openStream();

os = new FileOutputStream(new File("c:\\1.zip"));

int width = is.available();

byte[] b =new byte[width];

int i = 0;

while ((i = is.read(b)) > 0) {

os.write(b, 0, i);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if (os !=null) {

try {

os.close();

} catch (IOException e) {

}

}

if (is !=null) {

try {

is.close();

} catch (IOException e) {

}

}

}

}

public static void main(String[] args)throws Exception {

//new Client().downFile1();

new Client().upload();

}

}

=====================================================================

这里注意先要启动Tomcat服务器,再运行Client,在客户端会显示:上传成功

九、新建Spring测试类

package com.test;

import java.io.File;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

import com.util.CxfFileWrapper;

import com.util.FileInterface;

public class ClientWithSpring {

public void upload(){

ApplicationContext con = new ClassPathXmlApplicationContext("applicationContext.xml");

FileInterface fileinter = con.getBean("client",FileInterface.class);

CxfFileWrapper xcfile = new CxfFileWrapper();

xcfile.setFileName("LoginDB.bak");

xcfile.setFileExtension("bak");

String filePath = "D:\\ERPDB\\LoginDB.bak";

DataSource source = new FileDataSource(new File(filePath));

xcfile.setFile(new DataHandler(source));

boolean success = fileinter.upload(xcfile);

System.out.println(success ?"上传成功!":"上传失败!");

}

public static void main(String[] args)throws Exception {

new ClientWithSpring().upload();

}

}

启动Tomcat服务器,再运行ClientWithSpring,在客户端会显示:上传成功

已过而立之年的老码农,还在学习一些新知识!因为爱,所以坚持;因为上有老,下有小,所以也要坚持,致过了而立之年还在坚持写代码的码农们,在做好工作的前提下,好好陪陪家人孩子,有时间多回家看看父母,同时也要好好锻炼身体,毕竟你就是家里的天!!!……

代码下载地址:

http://download.csdn.net/detail/zhangshufei8001/9402666

猜你喜欢

转载自zhangshufei8001.iteye.com/blog/2377302
今日推荐