package cn.cd.sung.xml;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.junit.Test;
public class TestJaxb {
@Test
public void test1() throws JAXBException{
JAXBContext ctx = JAXBContext.newInstance(Student.class);
Marshaller marshaller = ctx.createMarshaller();
Student student = new Student(1, new ClassRoom(1,"10级计算应用技术","2010"), "孙刚", 22);
marshaller.marshal(student, System.out);
}
@Test
public void test2() throws JAXBException{
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>22</age><classRoom><grade>2010</grade><id>1</id><name>10级计算应用技术</name></classRoom><id>1</id><name>孙刚</name></student>";
JAXBContext ctx = JAXBContext.newInstance(Student.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
Student student = (Student) unmarshaller.unmarshal(new StringReader(xml));
System.out.println(student.getName() + ", " + student.getClassRoom().getName());
}
}
|
//===============================DTD:定义=============================
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT classroom (name,grade,students+)>
//#REQUIRED必须出现
<!ATTLIST classroom id ID #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT grade (#PCDATA)>
<!ELEMENT students (student)>
<!ELEMENT student (id,name,age)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
//============================xml引入DTD文件=================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE classroom SYSTEM "classroom.dtd">
<classroom id="c1">
<name>软件技术001</name>
<grade>201</grade>
<students>
<student>
<id>s1</id>
<name>孙刚</name>
<age>20</age>
</student>
</students>
<students>
<student>
<id>s2</id>
<name>孙刚</name>
<age>20</age>
</student>
</students>
</classroom>
//==========================Schema文件定义==================
//下面定义了一些 基本的Schema的 元素 属性等.
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/02"
xmlns:tns="http://www.example.org/02" elementFormDefault="qualified">
<element name="books">
<!-- 复杂类型 -->
<complexType>
<!--minOccurs最少出现数 maxOccurs最多出现数 -->
<sequence minOccurs="1" maxOccurs="unbounded">
<element name="book">
<complexType>
<!-- sequence 代表有顺序的 all可以不用顺序出现 -->
<sequence minOccurs="1">
<!--type 普通类型-->
<element name="bookname" type="string" />
<element name="content" type="string" />
<element name="author" type="string" />
<choice>
<element name="authors" block="#all">
<complexType>
<sequence maxOccurs="3">
<element name="author" type="string" />
</sequence>
</complexType>
</element>
</choice>
</sequence>
<!-- 定义属性 use 是否必须 optional 有没有都可以 "required" 必须有 属性定义必须在 sequence之后-->
<attribute name="id" type="int" use="required"/>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
//=======================XML引入Schema文件==================
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book ="http://www.example.org/02"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="02.xsd">
<book:book id="1">
<book:bookname>JAVA编程思想</book:bookname>
<book:content>JAVA</book:content>
<book:author>1</book:author>
<book:authors>
<book:author>2</book:author>
</book:authors>
</book:book>
<book:book id="2">
<book:bookname>SOAP</book:bookname>
<book:content>SOAP CONTENT</book:content>
<book:author>1</book:author>
<book:authors>
<book:author>2</book:author>
</book:authors>
</book:book>
</book:books>
//======================Schema文件定义 2==================
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/03"
xmlns:tns="http://www.example.org/03"
elementFormDefault="qualified">
<!-- tns 引入本文件的 Schema 元素 -->
<!-- 元素最大化 使用 优点:结构清晰 缺点:根源不清晰 books,id,title都可以使用根节点-->
<xsd:element name="books" type="tns:bookType"/>
<xsd:element name="id" type="int"/>
<xsd:element name="title" type="string"/>
<xsd:element name="contents" type="string"/>
<xsd:complexType name="bookType">
<xsd:sequence minOccurs="1" maxOccurs="unbounded">
<xsd:element ref="tns:id"/>
<xsd:element ref="tns:title"/>
<xsd:element ref="tns:contents"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
//======================Schema文件定义 3==================
<?xml version="1.0" encoding="UTF-8"?>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/04"
xmlns:tns="http://www.example.org/04"
elementFormDefault="qualified">
<!--一个 根节点 通过 simpleType 完成重用-->
<element name="person" type="tns:personType"/>
<complexType name="personType">
<sequence minOccurs="1" maxOccurs="unbounded">
<element name="name" type="string"/>
<element name="age" type="tns:ageType"/>
<element name="email" type="tns:emailType"/>
</sequence>
<attribute name="sex" type="tns:sexType"/>
</complexType>
<simpleType name="ageType">
<restriction base="int">
<!-- 最小包含 1 -->
<minInclusive value="1"/>
<maxInclusive value="150"/>
</restriction>
</simpleType>
<simpleType name="sexType">
<restriction base="string">
<enumeration value="男"/>
<enumeration value="女"/>
</restriction>
</simpleType>
<simpleType name="emailType">
<restriction base="string">
<!-- 正则验证 -->
<pattern value="(\w+\.*)*\w+@\w+\.[A-Za-z]{2,6}"></pattern>
<!-- 最小长度 -->
<minLength value="6"/>
<!-- 最大长度 -->
<maxLength value="255"/>
</restriction>
</simpleType>
</schema>
|
package cn.cd.sung.webservice.test;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
@WebService
public interface IMyService {
@WebResult(name="addResult")
public int add(@WebParam(name="a")int a,@WebParam(name="b")int b);
@WebResult(name="minusResult")
public int minus(@WebParam(name="a")int a,@WebParam(name="b")int b);
}
//=========================================================================
package cn.cd.sung.webservice.test;
import javax.jws.WebService;
@WebService(endpointInterface="cn.cd.sung.webservice.test.IMyService")
public class MySeviceImpl implements IMyService{
@Override
public int add(int a, int b) {
System.out.println(a + " + " + b + "=" + (a+b));
return a + b;
}
@Override
public int minus(int a, int b) {
System.out.println(a + " - " + b + "=" + (a-b));
return a - b;
}
}
//=============================发布服务端============================================
package cn.cd.sung.webservice.test;
import javax.xml.ws.Endpoint;
public class MyService {
public static void main(String[] args) {
String address = "http://localhost:1234/ns";
Endpoint.publish(address, new MySeviceImpl());
}
}
//之后可以直接在浏览器 输入http://localhost:1234/ns
//可以输入http://localhost:1234/ns?wsdl 查看wsdl文件
//=============================main 方法测试============================================
package cn.cd.sung.webservice.test;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class TestClient {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:1234/ns?wsdl");
QName qName = new QName("http://test.webservice.sung.cd.cn/", "MySeviceImplService");
Service service = Service.create(url, qName);
IMyService myService = service.getPort(IMyService.class);
System.out.println(myService.add(2, 3));
}
}
//=============================通过命令导出============================================
wsimport -d d:/webservice/01/ -keep -verbose http://localhost:1234/ns?wsdl
//-d d:/webservice/01/ : 制定生成目录
//-keep : 指定是否生成.java源代码
//-verbose : 指定生成详细过程
//http://localhost:1234/ns?wsdl : 网络中的wsdl文件
//生成:
Add.java
AddResponse.java
IMyService.java
Minus.java
MinusResponse.java
MySeviceImplService.java
ObjectFactory.java
package-info.java
//直接将此代码 拷贝走实用
//=============================Main 函数测试============================================
package cn.cd.sung.webservice.test;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class TestClient {
public static void main(String[] args) throws MalformedURLException {
//URL url = new URL("http://localhost:1234/ns?wsdl");
//QName qName = new QName("http://test.webservice.sung.cd.cn/", "MySeviceImplService");
//Service service = Service.create(url, qName);
//IMyService myService = service.getPort(IMyService.class);
//System.out.println(myService.add(2, 3));
MySeviceImplService service = new MySeviceImplService();
IMyService myService = service.getMySeviceImplPort();
System.out.println(myService.add(1, 3));
}
}
//一样效果调用服务端 webservice
|
package com.web.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.util.ContextUtil;
import com.opensymphony.xwork2.ActionContext;
public class WebServiceTool {
public final static String GET = "GET";
public final static String POST = "POST";
public final static String PUT = "PUT";
public final static String DELETE = "DELETE";
public final static Integer TIMEOUT = 5000;
public static void sendRest(String urlStr, Map<String, Object> params,
String method, WebServiceCallBack webServiceCallBack)
throws Exception {
if (GET.equalsIgnoreCase(method)) {
sendGet(urlStr, params, webServiceCallBack);
} else if (POST.equalsIgnoreCase(method)) {
sendPost(urlStr, params, webServiceCallBack);
}
}
public static void sendSoap(String urlStr, Map<String, String> headers,
String soapStr, WebServiceCallBack webServiceCallBack)
throws Exception {
URL url = new URL(urlStr);
HttpURLConnection httpURLConn = (HttpURLConnection) url
.openConnection();
httpURLConn.setDoInput(true);
httpURLConn.setDoOutput(true);
httpURLConn.setRequestMethod(POST);
httpURLConn.setConnectTimeout(TIMEOUT);
// 设置请求头
if (headers != null) {
for (String key : headers.keySet()) {
httpURLConn.setRequestProperty(key, headers.get(key));
}
}
httpURLConn.connect();
OutputStream out = null;
// 发送soap包
if (StringUtils.isNotBlank(soapStr)) {
out = httpURLConn.getOutputStream();
out.write(soapStr.getBytes());
out.flush();
}
String contentType = httpURLConn.getContentType();
// 获得响应流
InputStream in = httpURLConn.getInputStream();
webServiceCallBack.resultHandler(in, contentType);
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
public static void sendGet(String urlStr, Map<String, Object> params,
WebServiceCallBack webServiceCallBack) {
StringBuffer urlSb = new StringBuffer(urlStr);
int i = 0;
if (params != null) {
for (String key : params.keySet()) {
if (i++ == 0) {
urlSb.append("?");
} else {
urlSb.append("&");
}
urlSb.append(key);
urlSb.append("=");
urlSb.append(params.get(key));
}
}
URL url;
InputStream in = null;
try {
url = new URL(urlSb.toString());
HttpURLConnection httpURLConn = (HttpURLConnection) url
.openConnection();
httpURLConn.setDoInput(true);
httpURLConn.setDoOutput(true);
httpURLConn.setRequestMethod(GET);
httpURLConn.setConnectTimeout(TIMEOUT);
httpURLConn.connect();
String contentType = httpURLConn.getContentType();
in = httpURLConn.getInputStream();
webServiceCallBack.resultHandler(in, contentType);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void sendPost(String urlStr, Map<String, Object> params,
WebServiceCallBack webServiceCallBack) throws Exception {
StringBuffer paramStr = new StringBuffer();
int counter=0;
for (String key : params.keySet()) {
Object value = params.get(key);
paramStr.append(key).append("=").append(value);
if (++counter!=params.size()) {
paramStr.append("&");
}
}
URL url = new URL(urlStr);
HttpURLConnection httpURLConn = (HttpURLConnection) url
.openConnection();
httpURLConn.setDoInput(true);
httpURLConn.setDoOutput(true);
httpURLConn.setRequestMethod(POST);
httpURLConn.connect();
OutputStream out = httpURLConn.getOutputStream();
DataOutputStream serviceDataout = new DataOutputStream(
out);
serviceDataout.write(paramStr.toString().getBytes("UTF-8"));
String contentType = httpURLConn.getContentType();
InputStream in = httpURLConn.getInputStream();
webServiceCallBack.resultHandler(in, contentType);
}
public static String getSoap(String soapClassPath,
Map<String, Object> params) throws IOException {
String soapDiskPath = WebServiceTool.class.getResource(
"/" + soapClassPath).getPath();
StringBuffer soap = new StringBuffer();
InputStream in = new FileInputStream(soapDiskPath);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (params != null && params.size() > 0) {
for (String key : params.keySet()) {
line = line.replace("$" + key + "$", params.get(key) + "");
}
}
soap.append(line).append(System.getProperty("line.separator"));
}
return soap.toString();
}
}
package com.web.util;
import java.io.InputStream;
public interface WebServiceCallBack {
public void resultHandler(InputStream in,String contentType);
}
|