文档章节

JavaWebService攻略<1>Java WebService 入门

Zhao-Qian
 Zhao-Qian
发布于 2014/11/19 13:43
字数 2227
阅读 119
收藏 1
点赞 0
评论 0

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>







© 著作权归作者所有

共有 人打赏支持
Zhao-Qian
粉丝 309
博文 156
码字总数 237336
作品 0
朝阳
高级程序员
【目录导航】JAVA零基础进阶之路

【JAVA零基础入门系列】(已完结)导航目录 Day1 开发环境搭建 Day2 Java集成开发环境IDEA Day3 Java基本数据类型 Day4 变量与常量 Day5 Java中的运算符 Day6 Java字符串 Day7 Java输入与输出...

MFrank ⋅ 06/21 ⋅ 0

Java程序员必读书单,家族又添新成员

点击关注异步图书,置顶公众号 每天与你分享IT好书 技术干货 职场知识 参与文末话题讨论,每日赠送异步图书。 ——异步小编 有些革命出其不意地吸引了全世界的眼球。Twitter、Linux操作系统和...

异步社区 ⋅ 05/09 ⋅ 0

从Java小白到架构师必须要看的书籍,真正的“武林秘籍”!

少年,我看你骨骼精奇,将是未来万中无一的IT精英,很是适合学JAVA。维护世界和平就看你的了,我这里有能让你成为IT精英的办法!还不来看看! 基础类 1、《Thinking in Java》,入门第一位是...

启示录是真的 ⋅ 05/25 ⋅ 0

【小马哥】Spring Boot系列讲座

这里为大家推荐一个不错的Spring Boot系列讲座,讲师介绍如下: 小马哥,阿里巴巴技术专家,从事十余年Java EE 开发,国内微服务技术讲师。目前主要负责微服务技术推广、架构设计、基础设施、...

杜琪 ⋅ 03/02 ⋅ 0

学编程,学java还是大数据、android?平均月薪23k以上告诉你方向

学编程,学java还是大数据、android?有不少同学在纠结中,最近有不少初学者来问到,学习大数据,学习spark,公司主要使用那些语言编写,每听到这一个问题,起码还是很不错的,证明你已经开始...

编程南风 ⋅ 05/30 ⋅ 0

学java还是javascript好?哪个更有前途?

  对于哪种语言好这种问题,其实并没有固定的答案,最重要的还是 兴趣!兴趣!兴趣!重要的事情说三遍。无论做什么开发,永远要以兴趣来驱动自己学习。 先大致的说一下,Java学习是一个需要...

W3Cschool小编 ⋅ 04/23 ⋅ 0

java 10 的局部变量类型推导(Local Variable Type Inference )

其实说到变量类型推导,我们很容易连联想到一些脚本语言,在(http://openjdk.java.net/jeps/286)中,java提出这个新特性。 Enhance the Java Language to extend type inference to declar...

woshixin ⋅ 06/16 ⋅ 0

Java编程语言:学JAVA没有基础,给你4个方向少走弯路。

Java java常常跟"企业"联系在一起, 因为具备一些很好的语言特性, 以及丰富的框架, 在企业应用中最被青睐, 你总可以听到关于J2EE, JSP, Hibernate之类的东西的讨论. 同时, java在手机领域也有...

启示录是真的 ⋅ 05/24 ⋅ 0

《Spring技术内幕》学习笔记18——Spring使用Hessian实现远程调用

Spring目前提供了对RMI、 HttpInvoker、Hessian、Burlap及WebService等Remoting技术的集成。Spring屏蔽了这些实现技术的差异,用户只需开发简单的Java对象(Plain Old Java Objects,POJO)然后...

谜男amu ⋅ 05/16 ⋅ 0

叮!您收到一份超值Java基础入门资料!

摘要:Java语言有什么特点?如何最大效率的学习?深浅拷贝到底有何区别?阿里巴巴高级开发工程师为大家带来Java系统解读,带你掌握Java技术要领,突破重点难点,入门面向对象编程,以详细示例...

聒小小噪 ⋅ 05/12 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

Jenkins实践3 之脚本

#!/bin/sh# export PROJ_PATH=项目路径# export TOMCAT_PATH=tomcat路径killTomcat(){pid=`ps -ef | grep tomcat | grep java|awk '{print $2}'`echo "tom...

晨猫 ⋅ 今天 ⋅ 0

Spring Bean的生命周期

前言 Spring Bean 的生命周期在整个 Spring 中占有很重要的位置,掌握这些可以加深对 Spring 的理解。 首先看下生命周期图: 再谈生命周期之前有一点需要先明确: Spring 只帮我们管理单例模...

素雷 ⋅ 今天 ⋅ 0

zblog2.3版本的asp系统是否可以超越卢松松博客的流量[图]

最近访问zblog官网,发现zlbog-asp2.3版本已经进入测试阶段了,虽然正式版还没有发布,想必也不久了。那么作为aps纵横江湖十多年的今天,blog2.2版本应该已经成熟了,为什么还要发布这个2.3...

原创小博客 ⋅ 今天 ⋅ 0

聊聊spring cloud的HystrixCircuitBreakerConfiguration

序 本文主要研究一下spring cloud的HystrixCircuitBreakerConfiguration HystrixCircuitBreakerConfiguration spring-cloud-netflix-core-2.0.0.RELEASE-sources.jar!/org/springframework/......

go4it ⋅ 今天 ⋅ 0

二分查找

二分查找,也称折半查找、二分搜索,是一种在有序数组中查找某一特定元素的搜索算法。搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束;如果某一特定元素大于...

人觉非常君 ⋅ 今天 ⋅ 0

VS中使用X64汇编

需要注意的是,在X86项目中,可以使用__asm{}来嵌入汇编代码,但是在X64项目中,再也不能使用__asm{}来编写嵌入式汇编程序了,必须使用专门的.asm汇编文件来编写相应的汇编代码,然后在其它地...

simpower ⋅ 今天 ⋅ 0

ThreadPoolExecutor

ThreadPoolExecutor public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, ......

4rnold ⋅ 昨天 ⋅ 0

Java正无穷大、负无穷大以及NaN

问题来源:用Java代码写了一个计算公式,包含除法和对数和取反,在页面上出现了-infinity,不知道这是什么问题,网上找答案才明白意思是负的无穷大。 思考:为什么会出现这种情况呢?这是哪里...

young_chen ⋅ 昨天 ⋅ 0

前台对中文编码,后台解码

前台:encodeURI(sbzt) 后台:String param = URLDecoder.decode(sbzt,"UTF-8");

west_coast ⋅ 昨天 ⋅ 0

实验楼—MySQL基础课程-挑战3实验报告

按照文档要求创建数据库 sudo sercice mysql startwget http://labfile.oss.aliyuncs.com/courses/9/createdb2.sqlvim /home/shiyanlou/createdb2.sql#查看下数据库代码 代码创建了grade......

zhangjin7 ⋅ 昨天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部