---
title: "Web服务与SOA(二)"
author: "yefriendly"
date: "2009-05-01T16:46:20Z"
tags: ["SOA", "Servlet", "Tomcat", "Web", "XML"]
slug: "web-soa"
draft: false
lastmod: "2009-05-01T16:46:20Z"
id: 377850
url: "https://yefriendly.iteye.com/blog/377850"
---

转载自：[http://fengshen-xia.iteye.com/blog/293854](http://fengshen-xia.iteye.com/blog/293854)

翻译自"Service Oriented Architecture with Java"(使用Java开发面向服务的架构)一书之第二章

\[接上篇Web服务和SOA(一）] 现在，我们来看看如何使用 Java 实现 findById 这个 SOA 服务。我们将使用 JAXB 库来实现 XML 的自动绑定， JAXB 库已经包含在最新的 JDK6 中。因此，如果您使用的是 JDK6 ，您不需要下载额外的 jar 包，否则，您需要下载 JAXB ，并把它显式地加到您的服务器和客户端的类路径中。但是，因为下面的代码使用了 Java 注解功能 (Annotations) ，所以您需要 JDK5 或者更高版本编译和执行下面的代码。我们采用 Tomcat5.5 实现服务器端的 SOA 服务，实际上，我们只用了一个简单的 Servlet 来实现这个服务。

我们就动手写服务器和客户端的 Java 类来实现客户和服务器端的交互，这些类包括 Item 、 ItemAction 和 ItemActionResponse 。它们都是带有 Java 注解的 POJO 对象 (Plain Oil Java Objects) ， Java 注解在 XML 序列化和反序列化的过程中起了很重要的作用，示例代码如下所示：

代码清单 3 – XML 和注解进行绑定

 

01. @XmlRootElement (name= "Item" )
02. public   class  Item {
03. private   int  id;
04. private  String code;
05. private  String description;
06. ... getter/setter methods omitted ...
07. @XmlRootElement (name= "ItemAction" )
08. public   class  ItemAction{
09. private  String method;
10. private  Item item; ...
11. @XmlRootElement (name= "ItemActionResponse" )
12. public   class  ItemActionResponse {
13. private  String retCode;
14. private  Item item; ...

下面的代码是服务实现的主要部分，所有实现代码都包含在

Servlet 的 doPost() 方法中，该 Servlet 在 Web.xml 中的 URL 映射名为 itemCrudService 。

程序清单 4—itemCrudService 服务的服务器端实现

 

 

01. protected   void  doPost(HttpServletRequest request, HttpServletResponse response)
02. throws  ServletException, IOException
03. {
04. try {
05. JAXBContext jaxbContext = JAXBContext.newInstance (ItemAction. class , ItemActionResponse. class );
06. Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
07. //Receiving the XML request and transform it into a Java object
08. ItemAction itemAction = (ItemAction)
09. unmarshaller.unmarshal(request.getInputStream());
10. //Do some action depending on the request content
11. String method = itemAction.getMethod();
12. //Prepare the response as a Java object
13. ItemActionResponse itemActionResponse =  new  ItemActionResponse();
14. if  ( "findById" .equals(method)){
15. int  id = itemAction.getItem().getId();
16. //Retrieve item (e.g. from db)
17. Item item =  new  Item();
18. item.setId(id);
19. item.setCode( "Item XYZ" );
20. item.setDescription( "Description item XYZ" );
21. //Fill the response
22. itemActionResponse.setRetCode( "OK" );
23. itemActionResponse.setItem(item);
24. }
25. Marshaller marshaller = jaxbContext.createMarshaller();
26. marshaller.setProperty(Marshaller.JAXB\_FORMATTED\_OUTPUT,
27. Boolean.TRUE);
28. //The following line is not required, it was inserted
29. //just to see the content of the generated XML message
30. marshaller.marshal(itemActionResponse, System.out);
31. //Send the XML message to the client
32. marshaller.marshal( itemActionResponse,
33. response.getOutputStream());
34. }
35. catch  (JAXBException e){
36. throw   new  ServletException(e);
37. }
38. }

到现在为止，我们完成了一个基本服务的实现，其工作流程非常明了：

1\.        把 XML 请求序列化

2\.        进行处理操作

3\.        准备和序列化应答 XML

请注意上面的服务可供任何语言和技术调用，只要客户端程序能够对 XML 进行序列化和反序列化及对信息交换的协议有所了解即可。

  程序清单5 —itemCrudService 服务的客户端实现

 

01. //Prepare the request
02. ItemAction itemAction =  new  ItemAction();
03. Item item =  new  Item();
04. item.setId(26);
05. itemAction.setMethod( "findById" );
06. itemAction.setItem(item);
07. //Prepare and establish the connection with the service
08. URL url =  new  URL( "http://localhost/SoaBookPoxHttp/itemCrudService" );
09. HttpURLConnection con = (HttpURLConnection) url.openConnection();
10. con.setDoOutput( true );
11. //Set the HTTP request method
12. con.setRequestMethod( "POST" );
13. con.connect();
14. JAXBContext jaxbContext = JAXBContext.newInstance (ItemAction. class , ItemActionResponse. class );
15. Marshaller marshaller = jaxbContext.createMarshaller();
16. marshaller.setProperty(Marshaller.JAXB\_FORMATTED\_OUTPUT, Boolean.TRUE);
17. //The following line is not required, it was inserted
18. //just to see the content of the generated XML message
19. marshaller.marshal(itemAction, System. out );
20. //Send the XML request to the service
21. marshaller.marshal(itemAction, con.getOutputStream());
22. //Get the XML response from the service and deserialize it
23. Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
24. ItemActionResponse itemActionResponse = (ItemActionResponse)
25. unmarshaller.unmarshal(con.getInputStream());
26. //Show the response content
27. System. out .println( "retCode=" +itemActionResponse.getRetCode()+  "\\r"  +
28. "id=" +itemActionResponse.getItem().getId()+  "\\r"  +
29. "code=" +itemActionResponse.getItem().getCode()+  "\\r" + "description=" +itemActionResponse.getItem() .getDescription());

通过以上代码您会看到，所有参与消息交换的类

( 包括 Item, ItemAction 及 ItemActionResponse) 对客户端必须是可见的。在本例中，客户端和服务器端都使用 Java ，因此我们只需要简单地这些类从服务器端的项目中拷贝到客户端的项目中即可。但一般说来，这并不是必需的 ( 请思考一下如果客户端和服务器端使用不同语言的情况 ) 。服务实现过程中唯一的要求就是，您要传输的对象必须满足序列化和反序列化的要求。我们可以使用同样的方法来实现 findAllItems 服务，为此，我们新建一个 Servlet ，这个 Servlet 不需要任何输入，并返回所有的商品列表。该服务的实现代码如下：

 

程序清单 6—findAllItems 服务的服务器端实现

 

01. protected   void  doPost(HttpServletRequest request,
02. HttpServletResponse response)
03. throws  ServletException, IOException
04. {
05. try  {
06. JAXBContext jaxbContext = JAXBContext.newInstance (ItemList. class , Item. class );
07. ItemList itemList =  new  ItemList();
08. itemList.setList( new  ArrayList());
09. Item i1 =  new  Item();
10. i1.set ... ;
11. itemList.getList().add(i1);
12. ... populate itemList ...
13. Marshaller marshaller = jaxbContext.createMarshaller();
14. marshaller.setProperty(Marshaller.JAXB\_FORMATTED\_OUTPUT,
15. Boolean.TRUE);
16. //Just to see the content of the generated XML message
17. marshaller.marshal(itemList, System.out);
18. //Send the XML message to the client
19. marshaller.marshal(itemList, response.getOutputStream());
20. }
21. catch  (JAXBException e) {
22. throw   new  ServletException(e);
23. }
24. }

请注意，这里我们还需要定义一个

ItemList 类，其代码如下：

 

程序清单 7—ItemList 类的源代码

 

1. import  java.util.List;
2. import  javax.xml.bind.annotation.XmlRootElement;
3. @XmlRootElement (name= "ItemList" )
4. public   class  ItemList {
5. private  List list;
6. ...

相应的客户端测试代码应如下所示：

 

  程序清单 8— findAllItems 服务的客户端端测试代码

 

01. URL url =  new  URL( "http://localhost/SoaBookPoxHttp/findAllItems" );
02. HttpURLConnection con = (HttpURLConnection) url.openConnection();
03. con.setRequestMethod( "POST" );
04. con.connect();
05. //Void Request
06. //Get Response
07. JAXBContext jaxbContext = JAXBContext.newInstance (ItemList. class , Item. class );
08. Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
09. ItemList itemList = (ItemList)
10. unmarshaller.unmarshal(con.getInputStream());
11. for  (Iterator iterator = itemList.getList().iterator();
12. iterator.hasNext();)
13. {
14. Item item = (Item) iterator.next();
15. System.out.println( item.getId()+ " - " + item.getCode()+ " - " +
16. item.getDescription());
17. }

译者注：如果您想增加对

SOA 服务的理解，并有兴趣动手一试，请不妨补齐上面的源代码，看看能否在 Tomcat 中运行并通过测试。译者补齐了源代码并在 Tomcat6.0+Java6 的环境下测试通过，源代码的链接如下，供您参考。

[http://carllgc.blog.ccidnet.com/job-htm-action-download-itemid-777373-aid-86781.html](http://carllgc.blog.ccidnet.com/job-htm-action-download-itemid-777373-aid-86781.html)