JDK1.6原生态支持web服务,实现步骤如下:
1.创建一个pojo class,并添加相关注解:
package com.lemon.service; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; @WebService(name="Example", targetNamespace="http://www.jsoso.com/wstest", serviceName="Example") @SOAPBinding(style=SOAPBinding.Style.RPC) public class MyService { @WebMethod(operationName="toSayHello",action="sayHello",exclude=false) @WebResult(name="returnWord") public String sayHello(@WebParam(name="userName")String userName) { return "Hello:" + userName; } }
关于注解的说明:
Annotation 1@WebService(name="Example", targetNamespace="http://www.jsoso.com/wstest", serviceName="Example")
@WebService标签主要将类暴露为WebService,其中targetNamespace属性定义了自己的命名空间,serviceName则定义了< definitions >标签和<service>标签的name属性。
Annotation 2:@SOAPBinding(style=SOAPBinding.Style.RPC)
@SOAPBinding标签定义了WSDL文档中SOAP的消息协议,其中style属性对应SOAP的文档类型,可选的有RPC和DOCUMENT
Annotation 3:@WebMethod(operationName="toSayHello",action="sayHello",exclude=false)
@WebMethod定义Web Service运作的方法,
属性action 对应操作的活动 ,如<soap:operation soapAction="sayHello" />
属性operationName匹配的wsdl:operation 的名称,如<operation name="toSayHello" parameterOrder="userName">
属性exclude 用于阻止将某一继承方法公开为web服务,默认为false
Annotation 4:@WebResult(name="returnWord")
@ WebResult定义方法返回值得名称,如<part name="returnWord" type="xsd:string" />
Annotation 5:@WebParam(partName="person", mode=Mode.IN
@WebParam定义方法的参数名称,如<part name="person" type="tns:person" />,其中mode属性表示参数的流向,可选值有IN / OUT / INOUT
2.编写启动该服务的servlet:
package com.lemon.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.xml.ws.Endpoint; import com.lemon.service.MyService; public class StartWebServiceServlet extends HttpServlet { /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { System.out.println("准备启动服务"); Endpoint.publish("http://localhost:8080/javaWebservice", new MyService()); System.out.println("服务启动完毕"); } }
3.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>StartWebServiceServlet</servlet-name> <servlet-class>com.lemon.servlet.StartWebServiceServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
在浏览器中输入:http://localhost:8080/javaWebservice?wsdl 即可访问wsdl文件。