`
kakaluyi
  • 浏览: 437943 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

折腾了一把JAX-WS, SOA & Java EE 5(part 2 of 3)

阅读更多

4,把POJO或EJB搞成(呵呵)Web Service
可以将POJO或无状态EJB通过annotation的方式搞成Web Service。这些annotation包括@WebService,@WebMethod,WebParam
及@WebResult等。其属性都有却省值,但本文觉得有些参数不应该用缺省值。对本文的例子而言,@SOAPBinding 的属性之一
parameterStyle=SOAPBinding.ParameterStyle.BARE 是必须的,因为缺省值不合适。另外,@WebParam @WebResult
的属性targetNamespace也不能用缺省,而必须符合本文service Schema 的定义:"http://www.t50.com/portable"。

这些annotation将在部署时被服务器用来产生必要的service组件。察看WSDL将有助于理解这些annotation的参数的意义。

POJO通过annotation的方式搞成Web Service,该POJO应打包在.war中;无状态EJB通过annotation的方式搞成Web Service,
该ejb应打包在ejb-jar中。

下面是两个简单的例子:一个是本文前面提到的service GetPerson的pojo实现;一个是ejb的例子。pojo实现定义了business
interface,annotation 主要发生在该interface上。

pojo实现的business interface:-------------

{code}
package t50.service;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

import com.t50.portable.GetPersonRequest;
import com.t50.portable.GetPersonResponse;

/**
 * A web service business interface
 * <br/><br/> 
 * Would be implemented by container as a Servlet and therefore should be packaged in a war, e.g. t50.war
 * <br/><br/>
 * If parameter style is ParameterStyle.WRAPPED, it would expect Java built-in parameters and you could use
 * this url to test it with GlassFish: http://localhost:8080/t50/pojoWs?tester
 * <br/><br/>
 * However, this implementation uses ParameterStyle.BARE and it expects single request parameter. Therefore,
 * we really need a client program to send SOAP messages wrapping in our request payload to invoke the web service.
 * <br/><br/>
 * For a Stateless EJB exposed as a web service, it should be packaged in an ejb-jar, e.g. t50-ejb.jar
 * <br/>
 * @see t50.service.tes.SoapClient for a simple SOAP client.
 * @see t50.ejb.EJBYello for an EJB exposing similar method as web service.
 * <br/>
 * @author JWang
 */

@WebService
@SOAPBinding(
     style = SOAPBinding.Style.DOCUMENT,  // this is default value, rarely needs to change.  
     use = SOAPBinding.Use.LITERAL, // this is default value, rarely needs to change.
     //parameterStyle = SOAPBinding.ParameterStyle.WRAPPED  // the default value
     parameterStyle=SOAPBinding.ParameterStyle.BARE // when using your custom classes for @WebParam
)
public interface EchoWebService {
  
  @WebMethod
  @WebResult( name="getPersonResponse",
              targetNamespace="http://www.t50.com/portable",
              partName="getPersonResponse" )
  public GetPersonResponse sayHello( @WebParam(name="getPersonRequest",
                                               targetNamespace="http://www.t50.com/portable",
                                               partName="getPersonRequest" )
                                    GetPersonRequest request);
}
{code}


pojo实现---------------

{code}
package t50.service;

import javax.jws.WebService;

import org.apache.log4j.Logger;

import com.t50.portable.GetPersonRequest;
import com.t50.portable.GetPersonResponse;
import com.t50.portable.Person;

/**
 * web service implementation class - would be exposed as a Servlet
 * 
 * @author JWang
 *
 */
@WebService(serviceName="pojoEcho", endpointInterface="t50.service.EchoWebService")
public class EchoWebServiceImp implements EchoWebService {
  
  private static final Logger log = Logger.getLogger(EchoWebServiceImp.class);

  
  public GetPersonResponse sayHello(GetPersonRequest request) {
    
    if(request == null) {
      log.debug(EchoWebServiceImp.class.getName() + ":-( service request=null");
      return new GetPersonResponse();
    }
    
//    int pid = request.getPid();
//    log.debug("Getting person for pid: " + pid);
    
    
    Person person = request.getPerson();
    
    if(person == null) {
      log.debug("john, it's no good that person in request is null. set age to 89");
      person = new Person();
      person.setFirstName("john");
      person.setLastName("wang");
      person.setAge(89);
    }
    else {
      log.debug("john, everything goes well, lets set person's age to 30001");
      person.setAge(30001);  // this guy lives a pretty long life!
    }
    
    // construct response to return
    GetPersonResponse response = new GetPersonResponse();    
    response.setPerson(person);
    
    return response;
  }
}
{code}


ejb Remote Interface ----------------
{code}
package t50.ejb;

import javax.ejb.Remote;

@Remote
public interface YelloRemote {
  public String ejbHello(String s, int n);
}
{code}


ejb Implementation ------------------

{code}
package t50.ejb;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

/**
 * A Stateless EJB exposed as a web service, it should be packaged in a jar, e.g. t50-ejb.jar
 * Use this url to test it with GlassFish: http://localhost:8080/EJBYelloService/ejbWs?tester
 * 
 * If a POJO exposed as a web service, it should be packaged in a war, e.g. t50.war. 
 * Since it's implemented by the container as a servlet.
 * 
 * @author JWang
 *
 */

@Stateless
@WebService(name="ejbWs")
public class EJBYello implements YelloRemote {

  @WebMethod
  @WebResult(name="ejbHiBack")
  public String ejbHello( @WebParam(name="username") 
                          String aname,
                          @WebParam(name="userage")
                          int aage) {
    return "An EJB exposed as web service. params: username=" + aname + ", userage=" + aage;
  }
}
{code}


5,测试程序
经常看到用@WebServiceRef来实现webservice客户程序,这需要利用服务器提供的工具来产生必要的组件。既然
是SOAP web service,完全可以通过提交SOAP Message的方式来访问,而我们的请求内容(request payload)
将被包裹在所提交的SOAP message中:这也正是我们定义@XmlRootEelement(name="getPersonRequest")的意
义所在,这是通过jaxb进行数据绑定所必须的。

这样,我们可以将创建SOAP Message文件,然后用Java提供的SOAP API建立所需的SOAP Message,并提出请求。
以下是本文提到的GetPerson的测试程序SoapClient。值得注意的是,该测试程序除将返回的相应(response)存
未xml文件外,还利用jaxb api对其进行绑定处理(unmarshalling),直接得到"GetPersonResponse"对象,没
有手工解析(parse)返回的相应。这意味着service客户程序在处理返回的相应结果是有更方便的处理办法,完全
没有必要直接对xml文档进行手工处理。

这是运行SoapClient的终端输出:

Loading request payload: src/t50/service/test/xml/request/getPersonRequest.xml
Saving service response: src/t50/service/test/xml/tmp.xml
web service endpoint url: http://localhost:8080/t50/pojoEcho
Saving service response: src/t50/service/test/xml/response/getPersonResponse.xml
Printing this Person: com.t50.portable.Person: [firstName=john, lastName=wang, age=30001]


SoapClient.java ------------

{code}
package t50.service.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.ResourceBundle;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;

import t50.util.IOUtils;
import t50.util.StringUtils;

import com.t50.portable.GetPersonResponse;
import com.t50.portable.Person;


/**
 * A simple SOAP tester client
 * 
 * @author JWang
 *
 */
public class SoapClient {
  
  private static final ResourceBundle res = ResourceBundle.getBundle(SoapClient.class.getName());
  
  // "http://localhost:8080"
  private static final String host            = res.getString("host");
  // "/t50/pojoEcho"
  private static final String wscontext       = res.getString("wscontext");
  private static final String wsrequestfile   = res.getString("wsrequestfile");
  private static final String tmpfile         = res.getString("tmpfile");
  private static String wsresponsefile        = res.getString("wsresponsefile");
  
  
  public void testWebService() throws Exception {
    
    try {
      // construct request soap message
      SOAPMessage request = this.createSOAPMsgFromFile(wsrequestfile);
      
      // debug: save request to file
      this.saveFile(request, tmpfile);
      
      // construct web service url
      String wsurl = host + wscontext;
      URL endpoint = new URL(wsurl);
      
      System.out.println("web service endpoint url: " + wsurl);
      
      // send request to web service
      SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
      SOAPConnection connection = soapConnectionFactory.createConnection();
      
      SOAPMessage response = connection.call(request, endpoint);
      
      // save response to file
      this.saveFile(response, wsresponsefile);
      
      // try unmarshalling response
      SOAPBody body = response.getSOAPBody();
      Document doc = body.extractContentAsDocument();
      GetPersonResponse resp = (GetPersonResponse)this.unmarshall(doc, GetPersonResponse.class);
      
      this.printPerson(resp.getPerson());
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
  
  // debugging function
  private void printPerson(Person person) {
    if(person != null) {
      StringBuffer sb = new StringBuffer();
      sb.append("Printing this Person: ")
        .append(Person.class.getName()).append(": [")
        .append("firstName=").append(person.getFirstName())
        .append(", lastName=").append(person.getLastName())
        .append(", age=").append(person.getAge())
        .append("]");
      System.out.println(sb);
    }
  }
  
  private Object unmarshall(Document doc, Class clz) throws Exception {

    if(doc == null || clz == null) {
      return null;
    }
    
    // unmarshalls soap message to java object
    JAXBContext jc = JAXBContext.newInstance(clz);
    Unmarshaller um = jc.createUnmarshaller();
    
    // optional: do schema validation when unmarshalling service response if necessary
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File("doc/xsd/t50/person/GetPerson.xsd"));
    um.setSchema(schema);

    return um.unmarshal(doc);
  }

分享到:
评论

相关推荐

    jax-ws webservice demo

    基于jax-ws 实现的web service client和server端的demo程序。 注:如果使用的是 myeclipse 时 server 部署到tomcat 启动的时候会报错 解决办法:找到myeclipse安装目录下的 plugins 目录里 查找 webservices-rt.jar,...

    metro-jax-ws-master

    The Java API for XML Web Services (JAX-WS) is a Java programming language API for creating web services, particularly SOAP services.... It's a part of the Java SE and Java EE platforms.

    JAX-WS自学笔记

    JAX-WS自学笔记 本人自学JAX-WS笔记和简单例子,文档标题结构如下: JAX-WS使用教程 1、JAX-WS概述 2、创建Web Service 2.1 从java开始 2.1.1 运行wsgen 2.1.2 生成的WSDL和XSD 2.1.3 目录结构 2.2 从WSDL...

    JAX-WS 2.2 RI所有相关jar包

    JAX-WS 2.2 RI 所包含的JAR包集合,包含25个JAR包,列表如下: FastInoset.jar gmbal-api-only.jar ha-api.jar javax.annotation.jar javax.mail_1.4.jar jaxb-api.jar jaxb-impl.jar jaxb-xjc.jar jaxws-api...

    Jax-ws所需要的JAR包

    亲测可用,Jax-ws所需要的JAR包,拷贝到tomcat安装路径的lib里,实现了webservice发布到tomcat,赞!

    MyEclipse8_0中使用 JAX-WS 部署 WebService 实例

    MyEclipse8_0中使用 JAX-WS 部署 WebService 实例 - 外衣 - 博客频道 - CSDN_NET.mht

    JAX-WS2.0 API

    JAX-WS2.0 API

    JAX-WS_WebService.rar

    JAX-WS方式开发和部署webservice应用,JAX-WS方式开发和部署webservice应用,JAX-WS方式开发和部署webservice应用,JAX-WS方式开发和部署webservice应用,JAX-WS方式开发和部署webservice应用

    java实验_JAX-Ws

    可以更好的了解 jax-ws的实验过程。了解其原理

    Jax-WS 简单实例

    Jax-WS的简单实例 Jax-WS的简单实例

    webService部署tomcat需要的jax-ws jar包

    webService部署tomcat需要的jax-ws 的完整jar包

    jax-ws webservice简单demo

    jax-ws webservice完整demo,包含所有jax-ws 2.2jar包。

    JAX-WS 2.2 完整jar包

    JAX-WS 2.2 RI 所包含的JAR包集合,包含25个JAR包,列表如下: FastInoset.jar gmbal-api-only.jar ha-api.jar javax.annotation.jar javax.mail_1.4.jar jaxb-api.jar jaxb-impl.jar jaxb-xjc.jar jaxws-api...

    jax-rs jax-ws所需包,亲测可用

    javax.xml.ws.Service 报错需要的包,亲测可以用,直接下载在ide里buildpath一下就可以,四个jar包 ,整合了其他的jar所以配置简单

    JAX-WS开发的文件生成与部署相关全视频过程

    如果基于一个JAX-WS进行WebService开发,有很多教程,但是具体怎么更自动地生成一些文件,实现客户端与服务端的交互,都讲得不大清楚,为了让大家更方便地部署,我将服务端、客户端文件的生成与部署全过程以及测试...

    使用JAX-WS(JWS)发布WebService

    使用JAX-WS(JWS)发布WebService 使用myeclipse开发java的webservice的两种方式 方式一: (此方式只能作为调试,有以下bug:jdk1.6u17?以下编译器不支持以Endpoint.publish方式发布document方式的soap,必须在...

    JAX-WS2.2.6包

    JAX-WS规范是一组XML web services的JAVA API

    [Jax-RS] RESTful Java 开发 (Jax-RS 实现) (英文版)

    Learn how to design and develop distributed web services in Java using RESTful architectural principals and the JAX-RS specification in Java EE 6. With this hands-on reference, you'll focus on ...

    JAX-WS Web service

    JAX-WS Web service 开发初步

Global site tag (gtag.js) - Google Analytics