文档章节

JavaWebService攻略<1>Java WebService 入门

Credo-Zhao
 Credo-Zhao
发布于 2014/11/19 13:43
字数 2227
阅读 193
收藏 1

「深度学习福利」大神带你进阶工程师,立即查看>>>

Java Web 入门

本章代码: https://github.com/zhaoqian/study-test/tree/master/credo-test/src/main/java/org/credo/jaxws/study1

1.什么是web服务.

web服务是网络化应用程序的一种.主要基于HTTP超文本传输协议.
web服务的定义可以分为两大类型: 基于SOAP协议和基于Rest风格.

2.Webservice服务示例(Jax-ws)

基于SOAP的JavaWeb服务尽管可以只由单独的Java类来实现,但是遵从最佳实践原则,首先应该定义一个Java接口类,在此接口内声明Web服务需要完成或实现的业务方法。
通常这类接口被称为"SEI",即服务端点接口(Service Endpoint Interface)。
而与之对应的实现类被称为"SIB",即服务实现Bean(Service Implementation Bean)。

SEI示例: 
package org.credo.jaxws.study1;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.RPC)
public interface TimeSEIServer
{
	@WebMethod String getTimeAsString();
	@WebMethod Long getTimeAsLong();
}

SIB示例:

package org.credo.jaxws.study1;

import java.util.Date;

import javax.jws.WebService;

@WebService(endpointInterface="org.credo.jaxws.study1.TimeSEIServer")
public class TimeSIBServerImpl implements TimeSEIServer
{

	@Override
	public String getTimeAsString()
	{
		return new Date().toString();
	}

	@Override
	public Long getTimeAsLong()
	{
		return new Date().getTime();
	}

}
启动服务:
package org.credo.jaxws.study1;

import javax.xml.ws.Endpoint;

public class TimeServerPublisher
{

	public static void main(String[] args)
	{
		Endpoint.publish("http://127.0.0.1:9876/ts", new TimeSIBServerImpl());
	}

}

输入http://127.0.0.1:9876/ts 页面,即可看到如下数据

Web Services

Endpoint Information
Service Name: {http://study1.jaxws.credo.org/}TimeSIBServerImplService
Port Name: {http://study1.jaxws.credo.org/}TimeSIBServerImplPort
Address: http://127.0.0.1:9876/ts
WSDL: http://127.0.0.1:9876/ts?wsdl
Implementation class: org.credo.jaxws.study1.TimeSIBServerImpl

http://127.0.0.1:9876/ts?wsdl 则是这个webservice的wsdl.

<?xml version="1.0" encoding="UTF-8"?><!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.4-b01. --><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.4-b01. --><definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://study1.jaxws.credo.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://study1.jaxws.credo.org/" name="TimeSIBServerImplService">
<types></types>
<message name="getTimeAsString"></message>
<message name="getTimeAsStringResponse">
<part name="return" type="xsd:string"></part>
</message>
<message name="getTimeAsLong"></message>
<message name="getTimeAsLongResponse">
<part name="return" type="xsd:long"></part>
</message>
<portType name="TimeSEIServer">
<operation name="getTimeAsString">
<input wsam:Action="http://study1.jaxws.credo.org/TimeSEIServer/getTimeAsStringRequest" message="tns:getTimeAsString"></input>
<output wsam:Action="http://study1.jaxws.credo.org/TimeSEIServer/getTimeAsStringResponse" message="tns:getTimeAsStringResponse"></output>
</operation>
<operation name="getTimeAsLong">
<input wsam:Action="http://study1.jaxws.credo.org/TimeSEIServer/getTimeAsLongRequest" message="tns:getTimeAsLong"></input>
<output wsam:Action="http://study1.jaxws.credo.org/TimeSEIServer/getTimeAsLongResponse" message="tns:getTimeAsLongResponse"></output>
</operation>
</portType>
<binding name="TimeSIBServerImplPortBinding" type="tns:TimeSEIServer">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
<operation name="getTimeAsString">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal" namespace="http://study1.jaxws.credo.org/"></soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://study1.jaxws.credo.org/"></soap:body>
</output>
</operation>
<operation name="getTimeAsLong">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal" namespace="http://study1.jaxws.credo.org/"></soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://study1.jaxws.credo.org/"></soap:body>
</output>
</operation>
</binding>
<service name="TimeSIBServerImplService">
<port name="TimeSIBServerImplPort" binding="tns:TimeSIBServerImplPortBinding">
<soap:address location="http://127.0.0.1:9876/ts"></soap:address>
</port>
</service>
</definitions>

靠近wsdl前面部分的"portType"节.
该节将已经发布的Web服务提供的服务操作组织在一起.
在本例中,服务操作就是getTimeAsString和getTimeAsLong.是在SEI中定义,SIB中实现的两方法.WSDL的portType节点就像一个java接口.只提供了服务操作的抽象定义.而没有提供具体实现细节.在Web服务定义的每一个服务操作中都包括一个输入消息和输出消息.输入消息代表这web服务的输入参数.在Web服务运行时环境中,每一个输入,输出消息都是一个SOAP文档.
另外一部分是在WSDL后面的"service"节.
本例中URL: http://localhost:9876/ts 中所请求的服务的位置.这个URL通常成为服务端点(Service endpoint).由它来告诉调用服务的客户端.该服务增援才可以被访问.

总的来说,wsdl的组成如下

第一部分:

定义了服务接口,他在WSDL中由<message../>元素和<portType.../>两个元素组成,
其中<message.../>元素定义了操作的交互方式.
<portType.../>元素里则可以包含N个<operation.../>元素,每个<operation.../>元素代表一个允许远程调用的操作(就是方法).

第二部分:

定义了服务实现.由bindingservice元素组成
binding定义了特定的通信协议,数据编码模型和底层通信协议.将WebService服务接口定义映射到具体实现.
service元素就包含一系列的port元素,每个元素将把绑定机制,服务访问协议,端点地址结合在一起.

3.请求webservice服务示例

通过CXF 转换WSDL为Java文件,指定UTF-8
ApacheCXF wsdl2java 指定编码:
 wsdl2java -encoding utf-8 wsdl网址

apache cxf生成文件如下:

package org.credo.jaxws.study1.simpleRequest.cxfGenerate;

import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Action;

@WebService(targetNamespace = "http://study1.jaxws.credo.org/", name = "TimeSEIServer")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface TimeSEIServer {

    @WebResult(name = "return", targetNamespace = "http://study1.jaxws.credo.org/", partName = "return")
    @Action(input = "http://study1.jaxws.credo.org/TimeSEIServer/getTimeAsLongRequest", output = "http://study1.jaxws.credo.org/TimeSEIServer/getTimeAsLongResponse")
    @WebMethod
    public long getTimeAsLong();

    @WebResult(name = "return", targetNamespace = "http://study1.jaxws.credo.org/", partName = "return")
    @Action(input = "http://study1.jaxws.credo.org/TimeSEIServer/getTimeAsStringRequest", output = "http://study1.jaxws.credo.org/TimeSEIServer/getTimeAsStringResponse")
    @WebMethod
    public java.lang.String getTimeAsString();
}
另一个TimeSIBServerImplService
package org.credo.jaxws.study1.simpleRequest.cxfGenerate;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.Service;

@WebServiceClient(name = "TimeSIBServerImplService", 
                  wsdlLocation = "http://127.0.0.1:9876/ts?wsdl",
                  targetNamespace = "http://study1.jaxws.credo.org/") 
public class TimeSIBServerImplService extends Service {

    public final static URL WSDL_LOCATION;

    public final static QName SERVICE = new QName("http://study1.jaxws.credo.org/", "TimeSIBServerImplService");
    public final static QName TimeSIBServerImplPort = new QName("http://study1.jaxws.credo.org/", "TimeSIBServerImplPort");
    static {
        URL url = null;
        try {
            url = new URL("http://127.0.0.1:9876/ts?wsdl");
        } catch (MalformedURLException e) {
            java.util.logging.Logger.getLogger(TimeSIBServerImplService.class.getName())
                .log(java.util.logging.Level.INFO, 
                     "Can not initialize the default wsdl from {0}", "http://127.0.0.1:9876/ts?wsdl");
        }
        WSDL_LOCATION = url;
    }

    public TimeSIBServerImplService(URL wsdlLocation) {
        super(wsdlLocation, SERVICE);
    }

    public TimeSIBServerImplService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public TimeSIBServerImplService() {
        super(WSDL_LOCATION, SERVICE);
    }
    
    //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
    //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
    //compliant code instead.
    public TimeSIBServerImplService(WebServiceFeature ... features) {
        super(WSDL_LOCATION, SERVICE, features);
    }

    //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
    //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
    //compliant code instead.
    public TimeSIBServerImplService(URL wsdlLocation, WebServiceFeature ... features) {
        super(wsdlLocation, SERVICE, features);
    }

    //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
    //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
    //compliant code instead.
    public TimeSIBServerImplService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     *
     * @return
     *     returns TimeSEIServer
     */
    @WebEndpoint(name = "TimeSIBServerImplPort")
    public TimeSEIServer getTimeSIBServerImplPort() {
        return super.getPort(TimeSIBServerImplPort, TimeSEIServer.class);
    }

    /**
     * 
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns TimeSEIServer
     */
    @WebEndpoint(name = "TimeSIBServerImplPort")
    public TimeSEIServer getTimeSIBServerImplPort(WebServiceFeature... features) {
        return super.getPort(TimeSIBServerImplPort, TimeSEIServer.class, features);
    }

}
简单请求的main方法:
package org.credo.jaxws.study1.simpleRequest;

import java.net.MalformedURLException;
import java.net.URL;

import org.credo.jaxws.study1.simpleRequest.cxfGenerate.TimeSEIServer;
import org.credo.jaxws.study1.simpleRequest.cxfGenerate.TimeSIBServerImplService;
import org.credo.jaxws.study1.simpleRequest.webservicelog.LogResolver;

public class RequestTime
{

	public static void main(String[] args) throws MalformedURLException
	{
		String wsdl="http://127.0.0.1:9876/ts?wsdl";
		URL url=new  URL(wsdl);
		TimeSIBServerImplService service= new TimeSIBServerImplService(url);
		//service.setHandlerResolver(new LogResolver());
		TimeSEIServer timeSEIServer = service.getTimeSIBServerImplPort();
		System.out.println("timeSEIServer.getTimeAsLong():"+timeSEIServer.getTimeAsLong());
		System.out.println("timeSEIServer.getTimeAsString():"+timeSEIServer.getTimeAsString());
	}

}
输出:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:getTimeAsLong xmlns:ns2="http://study1.jaxws.credo.org/"/></S:Body></S:Envelope>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Header/><S:Body><ns2:getTimeAsLongResponse xmlns:ns2="http://study1.jaxws.credo.org/"><return>1416379645456</return></ns2:getTimeAsLongResponse></S:Body></S:Envelope>
timeSEIServer.getTimeAsLong():1416379645456
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:getTimeAsString xmlns:ns2="http://study1.jaxws.credo.org/"/></S:Body></S:Envelope>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Header/><S:Body><ns2:getTimeAsStringResponse xmlns:ns2="http://study1.jaxws.credo.org/"><return>Wed Nov 19 14:47:25 CST 2014</return></ns2:getTimeAsStringResponse></S:Body></S:Envelope>
timeSEIServer.getTimeAsString():Wed Nov 19 14:47:25 CST 2014

4.了解SOAP消息

A: Example  HTTP request for the TimeServer service

POST http://127.0.0.1:9876/ts HTTP/ 1.1
Accept: text/xml
Accept: multipart/*
Accept: application/soap
User-Agent: SOAP::Lite/Perl/0.69
Content-Length: 434
Content-Type: text/xml; charset=utf-8
SOAPAction: ""

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
 soap:encodingStyle="http:// schemas.xmlsoap.org/soap/encoding/"
 xmlns:soap="http://schemas.xmlsoap.org/soap/ envelope/"
 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:tns="http://ts.ch01/ xmlns:xsd ="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
 <tns:getTimeAsString xsi:nil="true" />
 </soap:Body>
</soap:Envelope>


解析:

1.这个HTTP请求的第一行指定了方法为POST.在SOAP请求中,通常都是POST方式.而不是get.因为只有POST请求才有body域,可以用它来封装一个SOAP消息.在第一行请求的URL之后是HTTP协议的版本号,1.1(现行版本.)

2.在HTTP头之后,都是一些由冒号分割的键值对.这些键值对在HTTP请求头中出现的顺序是任意的."Accept"键连续出现了3次.
以MIME(Multipurpose Internet Mail Extension)类型/子类型的方式出现.分别是 text/xml.  multpart/*和application/soap.这三个键值对分别表明了请求者客户端可以分别处理

  • 1.任意类型的XML文档.
  • 2.附带任意数量的不同类型文档的请求响应(SOAP消息通常可以有任意多个附件).
  • 3,一个SOAP文档.
"SOAPAction"键通常用来表示这个HTTP请求是一个Web服务请求,同时取值可以为空字符串.在本例中为控制.但其值也可能是请求的Web服务操作的名称.


3.SOAP主体: 两个回车换行.此行用来作为HTTP头数据和Body数据域的分割符.Body域在POST请求下通常是必须的.但可能为空.
本例中,HTTP的body域包含一个SOAP文档.一般被称为SOAP信封(SOAP Envelope).因为Envelope就是信封的意思.SOAP主体包含一个命名为"getTimeAsString" 的xml元素.这个名称也就是客户端调用的服务操作方法的名称.

B:返回信息

HTTP/1.1 200 OK
Content-Length: 323
Content-Type: text/xml; charset=utf-8
Client-Date: Mon, 28 Apr 2008 02:12:54 GMT
Client-Peer: 127.0.0.1:9876
Client-Response-Num: 1

<?xml version="1.0" ?>
<soapenv:Envelope
 xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soapenv:Body>
 <ans:getTimeAsStringResponse xmlns:ans="http://ts.ch01/">
 <return>Mon Apr 28 14:12:54 CST 2008</return>
 </ans:getTimeAsStringResponse>
 </soapenv:Body>
</soapenv:Envelope>







Credo-Zhao

Credo-Zhao

粉丝 311
博文 173
码字总数 247984
作品 0
朝阳
技术主管
私信 提问
加载中
请先登录后再评论。
我的架构演化笔记 功能1: 基本的用户注册

“咚咚”,一阵急促的敲门声, 我从睡梦中惊醒,我靠,这才几点,谁这么早, 开门一看,原来我的小表弟放暑假了,来南京玩,顺便说跟我后面学习一个网站是怎么做出来的。 于是有了下面的一段...

强子哥哥
2014/05/31
976
3
5分钟 maven3 快速入门指南

前提条件 你首先需要了解如何在电脑上安装软件。如果你不知道如何做到这一点,请询问你办公室,学校里的人,或花钱找人来解释这个给你。 不建议给Maven的服务邮箱来发邮件寻求支持。 安装Mav...

fanl1982
2014/01/23
1.2W
7
研究虚拟机--Jikes RVM

Jikes研究虚拟机(Jikes Research Virtual Machine,简称Jikes RVM)是一种成熟的用于执行Java程序的虚拟机,其早期版本与当前版本分别在通用公共许可证(CPL)与Eclipse公共许可证(EPL)下开...

匿名
2013/02/13
1.1K
0
Swing界面分析和调试工具--Swing Inspector

Swing Inspector是一个Java Swing/AWT用户界面分析和调试工具,功能与firebug类似,具有强大的Swing/AWT用户界面分析和调试相关功能。 适用于从java swing初级到高级的所有开发人员,能够快速...

匿名
2013/03/06
3.4K
0
Java™ 编译器--Janino

Janino是一个超级小但又超级快的Java™ 编译器. 它不仅能像javac工具那样讲一组源文件编译成字节码文件,还可以对一些Java表达式,代码块,类中的文本(class body)或者内存中源文件进行编译,...

匿名
2013/04/02
4.1K
0

没有更多内容

加载失败,请刷新页面

加载更多

您如何加速Eclipse? - How can you speed up Eclipse?

问题: How can you make the experience with Eclipse faster? 如何使Eclipse体验更快? For instance: I disable all the plugins I don't need (Mylyn, Subclipse, …). 例如: 我禁用了所......

fyin1314
22分钟前
9
0
百度地图SDK新版内测邀请

本文作者:用****9 百度地图开放平台为开发者提供七大基础服务能力,其中地图SDK和导航SDK是开发者广泛使用的重要基础服务,为了满足开发者更多使用需求以及提升开发者集成后的应用效果,本次...

百度开发者中心
前天
27
0
获取JavaScript数组中的所有唯一值(删除重复项) - Get all unique values in a JavaScript array (remove duplicates)

问题: I have an array of numbers that I need to make sure are unique. 我需要确定一个唯一的数字数组。 I found the code snippet below on the internet and it works great until th......

javail
今天
11
0
如何检查字符串是否为空? - How to check if the string is empty?

问题: Does Python have something like an empty string variable where you can do: Python是否有类似空字符串变量的内容可以在其中执行: if myString == string.empty: Regardless, wh......

富含淀粉
今天
19
0
您如何存储未跟踪的文件? - How do you stash an untracked file?

问题: I have changes to a file, plus a new file, and would like to use git stash to put them away while I switch to another task. 我对一个文件进行了更改,再加上一个新文件,并希......

技术盛宴
今天
39
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部