> Java > java지도 시간 > 본문

자바에서 웹서비스 메소드를 완성하는 방법 소개

黄舟
풀어 주다: 2017-05-15 09:46:52
원래의
2423명이 탐색했습니다.

이 글에서는 주로 Java로 간단한 웹 서비스를 구현하는 방법을 자세히 소개하고 있는데, 관심 있는 친구들은 참고해 보세요.

이 글의 예시는 Java에서 웹 서비스를 구현하는 방법을 공유합니다. 구체적인 코드는 참고용입니다.

테스트 후 버그는 jdk1.6.10 이하 버전을 사용하는 것이 좋습니다. 위

1. 정의인터페이스

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. 인터페이스 구현

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. 서비스 정의

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.

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

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();
 } 
 }
}
로그인 후 복사

【관련 추천】

1. 특별 추천: "php 프로그래머 Toolbox" V0.1 버전 다운로드

2. Java 무료 동영상 튜토리얼

3. YMP 온라인 매뉴얼

위 내용은 자바에서 웹서비스 메소드를 완성하는 방법 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿