Home Java javaTutorial Introduction to the method of completing web service mode in java

Introduction to the method of completing web service mode in java

May 15, 2017 am 09:46 AM
java webservice

This article mainly introduces in detail how to implement simple webservice in java, which has certain reference value. Interested friends can refer to it

The examples in this article share with you how to implement webservice in java. The specific code is for your reference. The specific content is as follows

##After testing, bugs will appear below jdk1.6.10. It is recommended to use version 10 or above

1. Definition

Interface

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);

}

Copy after login

2. Implement interface

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;

 }

 

}

Copy after login

3. Define service

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());

 }

}

Copy after login

4. Test service

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();

 }

 }

 

}

Copy after login

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

215

216

217

218

219

220

221

222

223

224

225

226

import java.io.IOException;

import java.io.StringReader;

import java.io.StringWriter;

import java.net.URL;

import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBException;

import javax.xml.bind.Marshaller;

import javax.xml.namespace.QName;

import javax.xml.soap.MessageFactory;

import javax.xml.soap.SOAPBody;

import javax.xml.soap.SOAPBodyElement;

import javax.xml.soap.SOAPEnvelope;

import javax.xml.soap.SOAPException;

import javax.xml.soap.SOAPHeader;

import javax.xml.soap.SOAPMessage;

import javax.xml.soap.SOAPPart;

import javax.xml.transform.Source;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.TransformerException;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.TransformerFactoryConfigurationError;

import javax.xml.transform.dom.DOMResult;

import javax.xml.transform.stream.StreamSource;

import javax.xml.ws.Dispatch;

import javax.xml.ws.Service;

import javax.xml.ws.soap.SOAPFaultException;

import javax.xml.xpath.XPath;

import javax.xml.xpath.XPathConstants;

import javax.xml.xpath.XPathExpressionException;

import javax.xml.xpath.XPathFactory;

import org.junit.Test;

import org.soap.service.User;

import org.w3c.dom.Document;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

public class TestSoap {

  

 private String ns = "http://service.soap.org/";

 private String wsdlUrl = "http://localhost:8989/ms?wsdl";

 @Test

 public void test01() {

 try {

  MessageFactory factory = MessageFactory.newInstance();

   

  SOAPMessage message = factory.createMessage();

  SOAPPart part = message.getSOAPPart();

  SOAPEnvelope envelope = part.getEnvelope();

  SOAPBody body = envelope.getBody();

  QName qname = new QName("http://java.zttc.edu.cn/webservice",

   "add","ns");//<ns:add xmlns="http://java.zttc.edu.cn/webservice"/>

  //body.addBodyElement(qname).setValue("<a>1</a><b>2</b>");

  SOAPBodyElement ele = body.addBodyElement(qname);

  ele.addChildElement("a").setValue("22");

  ele.addChildElement("b").setValue("33");

  message.writeTo(System.out);

 } catch (SOAPException e) {

  e.printStackTrace();

 } catch (IOException e) {

  e.printStackTrace();

 }

 }

  

 @Test

 public void test02() {

 try {

  URL url = new URL(wsdlUrl);

  QName sname = new QName(ns,"MyServiceImplService");

  Service service = Service.create(url,sname);

   

  Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),

   SOAPMessage.class, Service.Mode.MESSAGE);

   

  SOAPMessage msg = MessageFactory.newInstance().createMessage();

  SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();

  SOAPBody body = envelope.getBody();

   

  QName ename = new QName(ns,"add","nn");//<nn:add xmlns="xx"/>

  SOAPBodyElement ele = body.addBodyElement(ename);

  ele.addChildElement("a").setValue("22");

  ele.addChildElement("b").setValue("33");

  msg.writeTo(System.out);

  System.out.println("\n invoking.....");

   

   

  SOAPMessage response = dispatch.invoke(msg);

  response.writeTo(System.out);

  System.out.println();

   

  Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();

  String str = doc.getElementsByTagName("addResult").item(0).getTextContent();

  System.out.println(str);

 } catch (SOAPException e) {

  e.printStackTrace();

 } catch (IOException e) {

  e.printStackTrace();

 }

 }

  

 @Test

 public void test03() {

 try {

  URL url = new URL(wsdlUrl);

  QName sname = new QName(ns,"MyServiceImplService");

  Service service = Service.create(url,sname);

   

  Dispatch<Source> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),

   Source.class, Service.Mode.PAYLOAD);

   

  User user = new User(3,"zs","张三","11111");

  JAXBContext ctx = JAXBContext.newInstance(User.class);

  Marshaller mar = ctx.createMarshaller();

  mar.setProperty(Marshaller.JAXB_FRAGMENT, true);

  StringWriter writer= new StringWriter();

  mar.marshal(user, writer);

   

  String payload = "<nn:addUser xmlns:nn=\""+ns+"\">"+writer.toString()+"</nn:addUser>";

  System.out.println(payload);

  StreamSource rs = new StreamSource(new StringReader(payload));

   

  Source response = (Source)dispatch.invoke(rs);

   

  Transformer tran = TransformerFactory.newInstance().newTransformer();

  DOMResult result = new DOMResult();

  tran.transform(response, result);

   

  XPath xpath = XPathFactory.newInstance().newXPath();

  NodeList nl = (NodeList)xpath.evaluate("//user", result.getNode(),XPathConstants.NODESET);

  User ru = (User)ctx.createUnmarshaller().unmarshal(nl.item(0));

  System.out.println(ru.getNickname());

 } catch (IOException e) {

  e.printStackTrace();

 } catch (JAXBException e) {

  e.printStackTrace();

 } catch (TransformerConfigurationException e) {

  e.printStackTrace();

 } catch (TransformerFactoryConfigurationError e) {

  e.printStackTrace();

 } catch (TransformerException e) {

  e.printStackTrace();

 } catch (XPathExpressionException e) {

  e.printStackTrace();

 }

 }

  

 @Test

 public void test04() {

 try {

  URL url = new URL(wsdlUrl);

  QName sname = new QName(ns,"MyServiceImplService");

  Service service = Service.create(url,sname);

   

  Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),

   SOAPMessage.class, Service.Mode.MESSAGE);

   

  SOAPMessage msg = MessageFactory.newInstance().createMessage();

  SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();

  SOAPBody body = envelope.getBody();

   

  SOAPHeader header = envelope.getHeader();

  if(header==null) header = envelope.addHeader();

  QName hname = new QName(ns,"authInfo","nn");

  header.addHeaderElement(hname).setValue("aabbccdd");

   

  QName ename = new QName(ns,"list","nn");//<nn:add xmlns="xx"/>

  body.addBodyElement(ename);

  msg.writeTo(System.out);

  System.out.println("\n invoking.....");

   

   

  SOAPMessage response = dispatch.invoke(msg);

  response.writeTo(System.out);

  System.out.println();

   

  Document doc = response.getSOAPBody().extractContentAsDocument();

  NodeList nl = doc.getElementsByTagName("user");

  JAXBContext ctx = JAXBContext.newInstance(User.class);

  for(int i=0;i<nl.getLength();i++) {

  Node n = nl.item(i);

  User u = (User)ctx.createUnmarshaller().unmarshal(n);

  System.out.println(u.getNickname());

  }

 } catch (SOAPException e) {

  e.printStackTrace();

 } catch (IOException e) {

  e.printStackTrace();

 } catch (JAXBException e) {

  e.printStackTrace();

 }

 }

  

 @Test

 public void test05() {

 try {

  URL url = new URL(wsdlUrl);

  QName sname = new QName(ns,"MyServiceImplService");

  Service service = Service.create(url,sname);

   

  Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),

   SOAPMessage.class, Service.Mode.MESSAGE);

   

  SOAPMessage msg = MessageFactory.newInstance().createMessage();

  SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();

  SOAPBody body = envelope.getBody();

   

  QName ename = new QName(ns,"login","nn");//<nn:add xmlns="xx"/>

  SOAPBodyElement ele = body.addBodyElement(ename);

  ele.addChildElement("username").setValue("ss");

  ele.addChildElement("password").setValue("dd");

  msg.writeTo(System.out);

  System.out.println("\n invoking.....");

   

   

  SOAPMessage response = dispatch.invoke(msg);

  response.writeTo(System.out);

  System.out.println();

   

 } catch(SOAPFaultException e){

  System.out.println(e.getMessage());

 } catch (SOAPException e) {

  e.printStackTrace();

 } catch (IOException e) {

  e.printStackTrace();

 }

 }

}

Copy after login

【Related Recommendations】

1.

Special Recommendation: "php Programmer Toolbox" V0.1 version download

2.

Java Free Video Tutorial

3.

YMP Online Manual

The above is the detailed content of Introduction to the method of completing web service mode in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles