WebService之Axis2引擎的使用教程
来源:互联网 发布:java将图片生成二维码 编辑:程序博客网 时间:2024/06/09 18:00
一.Axis的简介
1.特性:
Apache Axis2 是Axis(Apache Extensible Interaction System 即阿帕奇可扩展交互系统)的后续版本,是新一代的SOAP引擎。采用名为 AXIOM(AXIs Object Model)的新核心XML(标准通用标记语言的子集)处理模型,利用新的XML解析器提供的灵活性按需构造对象模型。支持HTTP,SMTP,JMS,TCP传输协议。支持REST (Representational State Transfer)。
2.功能
- 发送、接收、处理SOAP消息
- 通过java创建web service(可以通过Eclipse开发)
- 通过WSDL为server和client生成实现类
- 简单地获得服务的WSDL
- 在发送或接收的SOAP消息中上传附件
二.下载和配置
1.下载地址:
2.配置
1.新建一个java Web项目,将下载的Axis2-1.6.2.zip包解压
2.将解压后的文件中,提取有用部分文件拷贝到项目中:
- 将解压得到的Webapp文件中axis2-web文件夹拷贝到项目的Webcontent目录下
- 将Webapp下的WEB-INF下的web.xml拷贝到项目的WebContent\WEB-INF下
- 将Axis2-1.6.2\repository\modules文件夹拷贝到项目的WebContent\WEB-INF下
- 将Axis2-1.6.2\lib中的jar包(包括endorsed文件夹,但不拷贝所有txt文件),拷贝到WebContent\WEB-INF\lib文件夹中
- 将Axis2-1.6.2\conf下的axis2.xml拷贝到项目的WebContent\WEB-INF下
- 最后复制一份模板:将Axis2-1.6.2\samples\version\src\sample\axisversion\META-INF文件夹,拷贝到项目的WebContent\WEB-INF\services\UserInfoService(手动新建文件夹,此名字可以自定义)中。
三.Webservice服务端应用的实现:
说明:服务端的功能即将项目ORM层获取到的数据,通过WebService服务发布。例如,通过MyBatis获取到数据库里的数据,提供一个Service接口来获取数据。通过Axis2将数据组装成OMElement对象,在通过Service.xml发布到tomcat服务器上。外界可以通过URL直接访问,获取数据。这是一种常见的webservice应用方式,下面我们来实现:
1.编写一个简单的JavaBean,模拟对数据库中一张表的映射,用来展示JavaBean转为XML对象的过程:
package com.webservice.bean;/* * 模拟:数据库表对应的JavaBean对象 */public class UserInfo { private String name; private String age; public UserInfo(String name, String age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }}
2.编写获取数据库数据的服务接口类:
package com.webservice.service;import java.util.ArrayList;import java.util.List;import javax.xml.namespace.QName;import org.apache.axiom.om.OMElement;import org.apache.axis2.databinding.utils.BeanUtil;import com.webservice.bean.UserInfo;public class UserInfoService { /** * 获取用户信息服务 * (做个示例,假设此服务取到数据库中的数据) * @return String xml * @throws Exception */ public OMElement getUserInfoData() { // 模拟取数据库值 List<Object> list = createListData(); // 对象转OMElement(根节点为:root,二级节点:indexDet) OMElement omElement = BeanUtil.getOMElement(new QName("root"), list.toArray(), new QName("indexDet"), false, null); return omElement; } /* * 生成假数据,模拟从数据库中取出了两组数据 */ private List<Object>createListData(){ List<Object> userInfo = new ArrayList<Object>(); UserInfo user1 = new UserInfo("张三","23"); UserInfo user2 = new UserInfo("李四","66"); userInfo.add(user1); userInfo.add(user2); return userInfo; }}
3.编写服务发布Service.xml配置文件,用来配置我们上面的服务接口:
<!-- 指定服务名,区分大小写,必须与Java服务类名相同 --><service name="UserInfoService"> <Description> Get JSON data </Description> <!-- 指定服务所在的包名 --> <parameter name="ServiceClass" locked="false"> com.webservice.service.UserInfoService </parameter> <messageReceivers> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" /> </messageReceivers> <operation name="getUserInfoData"> <!-- 指定URL访问别名 --> <actionMapping>urn:getUserInfoData</actionMapping> </operation></service>
4.发布和测试接口
在Tomcat中部署运行此项目,然后在浏览器中输入WSDL访问地址:http://localhost:8080/你的项目名/services/UserInfoService/getUserInfoData
打开后结果如下,则说明发布成功:
This XML file does not appear to have any style information associated with it. The document tree is shown below.<ns:getUserInfoDataResponse xmlns:ns="http://service.webservice.com"> <ns:return> <root> <indexDet> <age>23</age> <name>张三</name> </indexDet> <indexDet> <age>66</age> <name>李四</name> </indexDet> </root> </ns:return></ns:getUserInfoDataResponse>
若没有成功,请检查service.xml中的服务名和你项目中的服务名方法名是否对应,注意大小写敏感。
也可以输入:http://localhost:8080/你的项目名/services/UserInfoService?wsdl 若出现如下信息,则说明配置成功:
This XML file does not appear to have any style information associated with it. The document tree is shown below.<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns="http://service.webservice.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" targetNamespace="http://service.webservice.com"><wsdl:documentation>Get JSON data</wsdl:documentation> <wsdl:types> <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://service.webservice.com"> <xs:element name="getUserInfoData"> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name="getUserInfoDataResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="return" nillable="true" type="xs:anyType"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> </wsdl:types> 部分内容省略……
四.客户端应用的实现:
说明:WebService的第二种应用方式,客户端将本地数据通过WebService传递给他人的服务器,供他人使用我们的数据。
1.新建一个服务端,步骤同上,用来接收客户端的数据并解密(最好不要明文传递数据,附带讲解下加密),代码如下:
package com.today.ems.receive;import org.apache.axiom.om.impl.llom.OMTextImpl;import org.apache.log4j.Logger;import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;import com.today.ems.common.util.CommonUtil;import com.today.ems.common.util.DesUtil;/** * 测试接收客户端数据服务 * * @author today 2017/3/3 * @version 1.0 */public class ReceiveTest { private static Logger logger = Logger.getLogger(ReceiveTest.class); /** * 接收数据服务(接收多个参数) * * @param xml * @param aimWsMess * @return */ public String receiveXmlDataService(Object xml, Object aimWsMess) { String[] args = new String[] { "rltFlag", "rltMsg" }; Object[] values = new Object[] { "0", "调用接口失败" }; logger.info("————————————————接收数据开始————————————————"); try { DesUtil desUtil = new DesUtil("34#@23ASDFVgh&*^%#cbmGADSfLKJLJKdfalsdkj"); // 取出接收到的XML数据并解密 String xmlStr = new String(Base64.decode(((OMTextImpl) (xml)).getText())); logger.info("加密XML信息为:" + ((OMTextImpl) xml).getText()); logger.info("解密XML信息为:" + xmlStr); // 取出接收到报文头的数据 String aimWsMessStr = ((OMTextImpl) (aimWsMess)).getText(); // 通过invokeBlocking()方法传递byte[]参数时,会被Base64加密,所以要解密一次 byte[] aimWsMessByte = Base64.decode(aimWsMessStr); // 对数据Des解密 String aimStr = new String(desUtil.decrypt(aimWsMessByte)); logger.info("解密后报文头信息为:" + aimStr); logger.info("————————————————接收完成————————————————"); if (aimStr.length() != 0 && xmlStr.length()!=0) { values = new Object[] { "1", "调用接口成功" }; return CommonUtil.makeXML(args, values); } } catch (Exception e) { logger.info(CommonUtil.getExceptionStackTrace(e)); e.printStackTrace(); } return CommonUtil.makeXML(args, values); }}
2.服务端的Service.xml
<service name="receiveDataService"> <Description> Get Xml data </Description> <parameter name="ServiceClass" locked="false"> com.today.ems.receive.ReceiveTest </parameter> <messageReceivers> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" /> </messageReceivers> <operation name="receiveXmlData"> <actionMapping>urn:receiveXmlData</actionMapping> </operation> </service>
3.客户端发送数据实现类:
package com.service.client;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URL;import java.util.Properties;import javax.xml.namespace.QName;import org.apache.axiom.om.OMAbstractFactory;import org.apache.axiom.om.OMElement;import org.apache.axiom.om.OMFactory;import org.apache.axiom.om.OMNamespace;import org.apache.axiom.soap.SOAPFactory;import org.apache.axiom.soap.SOAPHeaderBlock;import org.apache.axis2.addressing.EndpointReference;import org.apache.axis2.client.Options;import org.apache.axis2.rpc.client.RPCServiceClient;import org.apache.axis2.transport.http.HTTPConstants;import org.apache.log4j.Logger;import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;import com.today.ems.common.util.CommonUtil;import com.today.ems.common.util.DesUtil;import com.todayt.ems.util.ExUtil;public class WebServiceImpl { private static Logger logger = Logger.getLogger(WebServiceImpl.class); private String ENCRYPT_KEY = "34#@23ASDFVgh&*^%#cbmGADSfLKJLJKdfalsdkj"; /** * @description 调用psm平台的webservice接口 * * @param sendXmlData * 数据库取出的信息 * @return 返回xml格式信息字符串 */ public String sendWs(String sendXmlData) { /** * 变量定义 */ String returnStrXml = "";// 返回信息 String[] aimWsMess = new String[7];//本地配置文件信息 aimWsMess[0] = "http://receive.ems.today.com";//服务器端的namespace命名空间,在WSDL中可以看到。 aimWsMess[1] = "http://localhost:8080/axis2/services/receiveDataService";//服务器端的接收数据接口URL地址 aimWsMess[2] = "receiveDataService";//服务类名:receiveDataService aimWsMess[3] = "commonWsService";// 这个是自定义的参数 aimWsMess[4] = "com.today.ems.receive.ReceiveTest";//服务器端的包名和类名 aimWsMess[5] = "receiveXmlData";//服务器端调用的方法名 aimWsMess[6] = "";// 这个是自定义的参数 // 获取总部webservice地址 String wsUrl = aimWsMess[1]; /** * wsUrl地址获取失败则直接返回 */ if (wsUrl == "") { if (logger.isInfoEnabled()) logger.debug("获取webservice地址失败!"); String[] args = new String[] { "errorCode", "errorMessage" }; Object[] values = new Object[] { "01", "获取webservice地址失败!" }; return CommonUtil.makeXML(args, values); } if (logger.isInfoEnabled()) logger.debug("获取总部webservice地址:" + wsUrl); /** * 记录请求日志 */ if (logger.isInfoEnabled()) { logger.debug("id为:" + "的用户发起了webservice请求"); logger.debug("请求服务串:" + sendXmlData); } /** * 利用base64对请求字符串进行编码 */ sendXmlData = Base64.encode(sendXmlData.getBytes()); /** * 连接通道测试 */ if (1 != ping(wsUrl)) { String[] args = new String[] { "errorCode", "errorMessage" }; Object[] values = new Object[] { "01", "服务端连接失败" }; return CommonUtil.makeXML(args, values); } try { /** * 调用axisUtil的发送方法 */ returnStrXml = accessCollWS(aimWsMess, new Object[] { sendXmlData, encrypt(aimWsMess, ENCRYPT_KEY) }); } catch (Exception e) { if (logger.isInfoEnabled()) logger.debug("服务端调用失败:", e); return returnStrXml; } finally { } return returnStrXml; } /** * 两级平台webservice接口调用(基于RPCServiceClien进行调用) * * @param aimWsMess * : 被调用webservice的相关信息 aimWsMess[0] 被调用webservice的目标命名空间 * aimWsMess[1] 被调用webservice的url aimWsMess[2] 被调用webservice的方法 * @param opAddEntryArgs * 参数 * @return xml形式的字符串 <data> <errorCode>code</errorCode> * <errorMessage>message</errorMessage> </data> 编码错误信息对照表: * 01:服务端连接失败! 02:服务端权限验证未通过! 03:服务端内部错误! 04:请求发送失败! 05:服务端未知错误! * 06:客户端未知错误! 07:被调用方法返回null或""! 08:业务处理信息! 09:客户端ip未绑定! * 99:业务校验失败信息! * */ @SuppressWarnings("unused") public String accessCollWS(String[] aimWsMess, Object[] opAddEntryArgs) throws Exception { try { // ModuleDelegatingClassLoader for // [me_opinformationpublish_1.0.0.qualifier javax.xml.stream.XMLOutputFactory xof = null; xof = new com.ctc.wstx.stax.WstxOutputFactory(); Class.forName("javax.xml.stream.XMLOutputFactory"); Class.forName("com.ctc.wstx.stax.WstxOutputFactory"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { // RPCServiceClient是RPC方式调用 RPCServiceClient client = new RPCServiceClient(); setSoapHeader(client, aimWsMess); Options options = client.getOptions(); // 设置调用WebService的URL EndpointReference epf = new EndpointReference(aimWsMess[1]); options.setTo(epf); // 设置超时时间 int timeout = 60000; options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(timeout)); options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, new Integer(timeout)); // 指定WSDL文件的命名空间和要调用的方法 // 参数一:该服务wsdl中的:targetNamespace="http://service.webservice.com" // 参数二:该服务中的一个方法名:monitorDailyFreezService QName qname = new QName(aimWsMess[0], aimWsMess[2]); Object[] result = null; Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); thread.setContextClassLoader(this.getClass().getClassLoader()); try { if (logger.isDebugEnabled()) { logger.debug("开始向服务端发送请求..."); } // invokeBlocking方法有三个参数,第一个参数的类型是QName对象,指定WSDL文件的命名空间和要调用的方法; // 第二个参数表示要调用的WebService方法的参数值,没有不能传null,而要使用new Object[]{} // 第三个参数表示WebService方法的返回值类型的Class对象,参数类型为Class[]。 result = client.invokeBlocking(qname, opAddEntryArgs, new Class[] { OMElement.class }); if (logger.isDebugEnabled()) { logger.debug("服务端返回信息:" + result[0]); } } catch (Exception e) { e.printStackTrace(); } finally { thread.setContextClassLoader(loader); client.cleanupTransport();// 关闭连接 } return String.valueOf(result[0]); } catch (Exception e) { e.printStackTrace(); if (logger.isInfoEnabled()) logger.debug("调用下行WebService服务失败:" + ExUtil.getExceptionStackTrace(e)); String[] args = new String[] { "errorCode", "errorMessage" }; Object[] values = new Object[] { "04", "请求发送出错:" + ExUtil.getExceptionStackTrace(e) }; return CommonUtil.makeXML(args, values); } } /* * 取beanId、clazz、methodName、userId的合成串进行加密 * * @return 返回加密后的字符串 */ private static byte[] encrypt(String[] aimWsMess, String encryptKey) { try { // 获取被加密串(截取部分数组) String encryptStr = aimWsMess[3] + aimWsMess[4] + aimWsMess[5] + aimWsMess[6]; // 从配置文件获取密钥字符串 DesUtil du = new DesUtil(encryptKey); byte[] encryptStrByte = encryptStr.getBytes("gbk"); // 加密 byte[] ek = du.encrypt(encryptStrByte); return ek; } catch (Exception e) { if (logger.isInfoEnabled()) logger.debug("验证请求串加密失败:" + e.getStackTrace()); return null; } } /** * * 测试Web服务是否正常 * * @return 成功/失败标志 (1表示成功,0表示失败) */ public int ping(String wsUrl) { if (logger.isDebugEnabled()) { logger.debug("开始测试连接通道..."); } // < 100 is undertermined. // 1nn is informal (shouldn't happen on a GET/HEAD) // 2nn is success // 3nn is redirect // 4nn is client error // 5nn is server error try { // String wsUrl = PropertyRead.getString("WS_URL"); String urlstr = wsUrl + "?wsdl"; if (logger.isInfoEnabled()) logger.debug("测试通道wsUrl地址:" + wsUrl); HttpURLConnection connection = (HttpURLConnection) new URL(urlstr).openConnection(); // connection.setRequestMethod("HEAD"); // ? ResponseCode() == 501 connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); // String msg = connection.getResponseMessage(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { connection.disconnect(); if (logger.isDebugEnabled()) { logger.debug("成功连接到服务端!"); } return 1; } } catch (MalformedURLException ex) { } catch (ProtocolException ex) { } catch (IOException ex) { } if (logger.isDebugEnabled()) { logger.debug("无法连通服务端!"); } return 0; } /** * 设置soap的header信息,主要在header中追加用户名和密码,以作身份认证 * * @param client * Soap客户端对象 * */ public void setSoapHeader(RPCServiceClient client, String[] aimWsMess) throws Exception { try { // RPCServiceClient是RPC方式调用 SOAPFactory factory = OMAbstractFactory.getSOAP12Factory(); OMFactory omfactory = OMAbstractFactory.getOMFactory(); OMNamespace omnames = omfactory.createOMNamespace("http://ws.apache.org/axis2", "hns"); SOAPHeaderBlock soapHeader; soapHeader = factory.createSOAPHeaderBlock("field", omnames); // 加入header OMElement beanIdElement = factory.createOMElement("beanId", null); beanIdElement.addChild(factory.createOMText(beanIdElement, aimWsMess[3])); OMElement clazzElement = factory.createOMElement("clazz", null); clazzElement.addChild(factory.createOMText(clazzElement, aimWsMess[4])); OMElement methodNameElement = factory.createOMElement("methodName", null); methodNameElement.addChild(factory.createOMText(methodNameElement, aimWsMess[5])); OMElement userIdElement = factory.createOMElement("userId", null); userIdElement.addChild(factory.createOMText(userIdElement, aimWsMess[6]));// 用户Id soapHeader.addChild(beanIdElement); soapHeader.addChild(clazzElement); soapHeader.addChild(methodNameElement); soapHeader.addChild(userIdElement); client.addHeader(soapHeader); } catch (Exception ex) { if (logger.isInfoEnabled()) logger.debug("Soap Header 信息设置出错:" + ExUtil.getExceptionStackTrace(ex)); throw new Exception(ExUtil.getExceptionStackTrace(ex)); } }}
4.客户端类:运行测试即可。
package com.service.client;import org.apache.axiom.om.OMElement;import com.webservice.service.UserInfoService;public class WebServiceClient { public String sendData() { String resultXml = ""; //调用服务,取到模拟数据库中的数据 UserInfoService service = new UserInfoService(); OMElement omElement = service.getUserInfoData(); //通过Webservice发送数据 WebServiceImpl wsImpl = new WebServiceImpl(); resultXml = wsImpl.sendWs(omElement.toString()); //返回Xml格式的返回信息 return resultXml; } //单元测试:测试发送数据 public static void main(String[] args) { WebServiceClient client = new WebServiceClient(); String resultStr = client.sendData(); System.out.println(resultStr); }}
5.用到的加密类:
package com.today.ems.common.util;import java.security.Key;import java.security.Security;import javax.crypto.Cipher;public class DesUtil { /** 字符串默认键值 */ private static String strDefaultKey = "34#@23ASDFVgh&*^%#cbmGADSfLKJLJKdfalsdkj"; /** 加密工具 */ private Cipher encryptCipher = null; /** 解密工具 */ private Cipher decryptCipher = null; /** * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] * hexStr2ByteArr(String strIn) 互为可逆的转换过程 * * @param arrB * 需要转换的byte数组 * @return 转换后的字符串 * @throws Exception * 本方法不处理任何异常,所有异常全部抛出 */ public static String byteArr2HexStr(byte[] arrB) throws Exception { int iLen = arrB.length; // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍 StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i < iLen; i++) { int intTmp = arrB[i]; // 把负数转换为正数 while (intTmp < 0) { intTmp = intTmp + 256; } // 小于0F的数需要在前面补0 if (intTmp < 16) { sb.append("0"); } sb.append(Integer.toString(intTmp, 16)); } return sb.toString(); } /** * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) * 互为可逆的转换过程 * * @param strIn * 需要转换的字符串 * @return 转换后的byte数组 * @throws Exception * 本方法不处理任何异常,所有异常全部抛出 * @author <a href="mailto:leo841001@163.com">LiGuoQing</a> */ public static byte[] hexStr2ByteArr(String strIn) throws Exception { byte[] arrB = strIn.getBytes(); int iLen = arrB.length; // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2 byte[] arrOut = new byte[iLen / 2]; for (int i = 0; i < iLen; i = i + 2) { String strTmp = new String(arrB, i, 2); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16); } return arrOut; } /** * 默认构造方法,使用默认密钥 * * @throws Exception */ public DesUtil() throws Exception { this(strDefaultKey); } /** * 指定密钥构造方法 * * @param strKey * 指定的密钥 * @throws Exception */ public DesUtil(String strKey) throws Exception { Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes()); encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } /** * 加密字节数组 * * @param arrB * 需加密的字节数组 * @return 加密后的字节数组 * @throws Exception */ public byte[] encrypt(byte[] arrB) throws Exception { return encryptCipher.doFinal(arrB); } /** * 加密字符串 * * @param strIn * 需加密的字符串 * @return 加密后的字符串 * @throws Exception */ public String encrypt(String strIn) throws Exception { return byteArr2HexStr(encrypt(strIn.getBytes())); } /** * 解密字节数组 * * @param arrB * 需解密的字节数组 * @return 解密后的字节数组 * @throws Exception */ public byte[] decrypt(byte[] arrB) throws Exception { return decryptCipher.doFinal(arrB); } /** * 解密字符串 * * @param strIn * 需解密的字符串 * @return 解密后的字符串 * @throws Exception */ public String decrypt(String strIn) throws Exception { return new String(decrypt(hexStr2ByteArr(strIn))); } /** * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 * * @param arrBTmp * 构成该字符串的字节数组 * @return 生成的密钥 * @throws java.lang.Exception */ private Key getKey(byte[] arrBTmp) throws Exception { // 创建一个空的8位字节数组(默认值为0) byte[] arrB = new byte[8]; // 将原始字节数组转换为8位 for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } // 生成密钥 Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key; } public static void main(String[] args) { try { String test = "x:\\file1\\test.swf"; DesUtil des = new DesUtil("SGCC201304241548");// 自定义密钥 System.out.println("加密前的字符:" + test); System.out.println("加密后的字符:" + des.encrypt(test)); System.out.println("解密后的字符:" + des.decrypt(des.encrypt(test))); } catch (Exception e) { e.printStackTrace(); } }}
6.用到的工具类
package com.today.ems.common.util;public class CommonUtil { /** * 生成指定参数的XML字符串 * * @param args * 参数 * @param values * 参数值 * @return 返回组装好的XML字符串 */ public static String makeXML(String[] args, Object[] values) { StringBuilder sb = new StringBuilder(); // sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); // sb.append("<DBSET>"); sb.append("<data>"); for (int i = 0; i < args.length; i++) { sb.append("<"); sb.append(args[i]); sb.append(">"); sb.append(values[i]); sb.append("</"); sb.append(args[i]); sb.append(">"); } sb.append("</data>"); // sb.append("</DBSET>");// System.out.println("makeXML()" + "生成指定参数的XML字符串:" + sb.toString()); return sb.toString(); } /** * 获取异常信息堆栈字符串 * */ public static String getExceptionStackTrace(Exception e) { String stackTrace = ""; StackTraceElement[] ste = e.getStackTrace(); for (int i = 0; i < ste.length; i++) { stackTrace += "\n" + ste[i] + "\n"; } return stackTrace; }}
7.异常处理类:
/** * Filename is com.today.common.TException.java * Copyright (C) 2013 TodayEnergy. All Rights Reserved. */package com.today.ems.common;/** * <strong>TException</strong> Class. * * @author today * @version 1.0 2013/12/13 */public class TException extends Exception { /** serialVersionUID */ private static final long serialVersionUID = 1L; /** * constructor */ public TException() { super(); } /** * constructor * @param message Message */ public TException(String message) { super(message); } /** * constructor * @param cause Throwable */ public TException(Throwable cause) { super(cause); } /** * constructor * @param message Message * @param cause Throwable */ public TException(String message, Throwable cause) { super(message, cause); }}
- WebService之Axis2引擎的使用教程
- WebService之Axis2系列教程(一)Axis2的下载、安装和使用
- WebService之Axis2系列教程(一)Axis2的下载、安装和使用
- WebService之Axis2系列教程(一)Axis2的下载、安装和使用
- WebService之Axis2系列教程(一)Axis2的下载、安装和使用
- WebService之Axis2系列教程(三)Axis2复合类型数据的传递
- WebService之Axis2系列教程(四)使用services.xml文件发布WebService
- WebService之Axis2系列教程Axis2与Spring集成发布
- WebService之Axis2系列教程(二)用POJO实现零配置的WebService
- WebService之Axis2系列教程(七)异步调用WebService
- axis2开发webservice教程
- Axis2(WebService)经典教程
- axis2开发webservice教程
- axis2客户端调用免费的webservice服务的实例之三axis2使用RPC方式调用网上免费WebService
- Axis2是目前比较流行的WebService引擎
- WebService之Axis2 使用services.xml文件发布WebService
- axis2实现webservice之使用services.xml文件发布WebService
- Axis2使用WebService的客户端实例
- Django module学习之模板
- 安卓学习笔记 6-10 热更新
- mysql之 mysql 5.6不停机主主搭建(活跃双主基于日志点复制)
- keras——常用层
- Unity3D基本入门及功能介绍
- WebService之Axis2引擎的使用教程
- JavaScript之异步
- 杭电POJ-2161-Primes
- 堡垒机的实现
- pl/sqldeveloper远程连接数据库方法
- linux应用调试技术之GDB和GDBServer
- 设计模式之适配器模式
- Java多线程之synchronized与Lock
- JavaWeb实现文件上传下载功能实例解析