本文实例为大家分享了java实现webservice方式的具体代码,供大家参考,具体内容如下
经过测试 jdk1.6.10以下会出现bug 建议使用10以上版本
1、定义接口
?
1
2
3
4
5
6
7
8
9
10
11
12
|
package org.enson.chan;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
@WebService
@SOAPBinding (style=SOAPBinding.Style.RPC)
public interface IMyService {
public int add( int a , int b);
public int max( int a , int b);
}
|
2、实现接口
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package org.enson.chan;
import javax.jws.WebService;
@WebService (endpointInterface= "org.enson.chan.IMyService" )
public class MyServiceImpl implements IMyService {
public int add( int a, int b) {
System.out.println(a+ "+" +b+ "=" +(a+b));
return a+b;
}
public int max( int a, int b) {
System.out.println( "a与b比较大小,取大值" +((a>b)?a:b));
return (a>b)?a:b;
}
}
|
3、定义服务
?
1
2
3
4
5
6
7
8
9
10
11
|
package org.enson.chan;
import javax.xml.ws.Endpoint;
public class MyServer {
public static void main(String[] args) {
String address = "http://localhost:8090/ns" ;
Endpoint.publish(address, new MyServiceImpl());
}
}
|
4、测试服务
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package org.enson.chan;
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) {
try {
URL url = new URL( "http://localhost:8090/ns?wsdl" );
QName sname = new QName( "http://chan.enson.org/" , "MyServiceImplService" );
//创建服务
Service service = Service.create(url,sname);
//实现接口
IMyService ms = service.getPort(IMyService. class );
System.out.println(ms.add( 12 , 33 ));
//以上服务有问题,依然依赖于IMyServie接口
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
5、TestSoap
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
|