Java Web - Build a Java Web Service and Client Sample by Eclipse

之前有修改過Web Service Client的程式,因此對於要如何建置一Web Service程式感到興趣。

後來發現原來Eclipse可以協助我們產生相關的WSDL描述檔及相關的library,並且Clinet端

的程式也可以透過Web Service的wsdl自動產生。因此在這邊就自行寫了一個簡單的Web

Service and Client範例。

在此,小弟不會說明Web Service的定義與特別介紹,在這個網站有很清楚的說明。

而小弟透過這個網站的說明,才知道如何建置一Java Web Service and Client,但發現有些地

方透過自己建置的過程,摸索到一點心得藉此另做記錄。

建構Web Service

首先建立一Dynamic Web Project,另target runtime的tomcat 7請自行先設定好


將撰寫的Java檔編譯至WEB-INF下的classes目錄內

撰寫一RecordInformations.java,並定義兩個method(接口),提供Client端能夠傳送資料至此

做記錄,及可以提供查詢使用!

相關code如下:

public String uploadRecord(String uploadid, String xmlcontent){
  String returnMsg = "upload data success!!";
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  SAXBuilder builder = new SAXBuilder();
  if(processRecords == null)processRecords = new ArrayList<Record>();
  try {
   Document document = (Document) builder.build(
                  new ByteArrayInputStream(xmlcontent.getBytes("utf-8")));
   Element rootNode = document.getRootElement();
   List<?> list = rootNode.getChildren("records");
   if(list.size() > 0){
    Element node = (Element) list.get(0);
    System.out.println("title : " + node.getChildText("title"));
    System.out.println("author : " + node.getChildText("author"));
    System.out.println("content : " + node.getChildText("content"));
    Record bean = new Record(uploadid);
    bean.setAuthor(node.getChildText("author"));
    bean.setContent(node.getChildText("content"));
    bean.setTitle(node.getChildText("title"));
    bean.setUploaddate(sdf.format(
               new java.sql.Date(System.currentTimeMillis())));
    processRecords.add(bean);
   }else{
    returnMsg = "upload data format error!!";
   }
  } catch (JDOMException | IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return returnMsg;
 }

uploadRecord method,將由Client端傳送一自行產生的ID及XML檔案格式的資料,範例如下:
<?xml version='1.0' encoding='UTF-8'?>
<document>
 <records>
  <title>2014舒跑杯競賽</title>
  <author>zhi.bin.huang</author>
  <content>OOXXOOXX</content>
 </records>
</document>

接下來,service將此XML資料做parse,並建立一Record,add to processRecords內

private static List<Record> processRecords;

另showRecord method主要為提供client端能夠顯示目前記錄多少Record供查詢使用

public String showRecord(){
 JSONArray records = new JSONArray();
 if(processRecords != null){
  Iterator<Record> list = processRecords.iterator();
  while(list.hasNext()) {
   Record record = list.next();
   JSONObject data = new JSONObject();
   data.put("uploaddate", record.getUploaddate());
   data.put("title", record.getTitle());
   data.put("author", record.getAuthor());
   data.put("content", record.getContent());
   
   records.add(data);
  }
  System.out.println("==>"+records.toString());
  return records.toString();
 }else{
  return "nodata";
 }
}

PS. Record這支Java Bean程式請自行建立囉!

發佈Web Service

針對RecordWebService專案來建置Web Service



Service implementation請選擇剛剛建立的Java實作檔

左邊的bar在一開始建立Web Service時,建議拉至Start Service




啟用Eclipse內的tomcat 7 server


至瀏覽器內執行http://localhost:8080/RecordWebService/services/RecordInformations?wsdl


如此一來Web Service已正常啟用!!


建立Web Service Client

請建立一Dynamic Web Project,同上

建立好之後,請針對該專案建立一Web Service Client



請將Web Service描述檔的URL貼至Service definition內,請注意Web Service需為啟用狀態

另在這邊小弟我只將左邊的bar拉至Install client,如果拉至最高系統會協助你建立範例檔案


前端畫面


前端程式 - JSP

<html ng-app="recordApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Record Web Service</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<script src="js/angular.js"></script>
<script src="js/jquery-2.1.3.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
 angular.module('recordApp', [])
  .controller('MainCtrl', ['$http', function($http){
   var self = this;
   self.records = [];
   self.showRecord = false;
   self.queryRecords = function(){
    $http.get('/WebServiceTest/QueryRecordService'
    ).then(function(response){
     if(response.data == 'nodata'){
      alert("目前無任何資料!!");
     }else{
      self.showRecord = true;
      self.records = response.data;
     }
    }, function(errResponse){
     alert('連接Web Service出錯!');
    });
   };
   
   self.submitRecord = function(){
    $http.post('/WebServiceTest/ConnectRecordService',
      {title:self.title, 
          author:self.selectAuthor, 
          content:self.content}
    ).then(function(response){
     alert(response.data);
    }, function(response){
     alert("failed!!");
    });
   };
  }]);
</script>
</head>
<body ng-controller="MainCtrl as ctrl">
<form name="myForm" ng-submit="ctrl.submitRecord()">
<table class="table" style="width:30%">
 <tr>
  <td>標題:</td>
  <td><input type="text" name="title" size="30" 
    ng-model="ctrl.title" required /></td>
 </tr>
 <tr>
  <td>作者:</td>
  <td>
  <select ng-model="ctrl.selectAuthor" required>
   <option value="小彬">小彬</option>
   <option value="小美">小美</option>
   <option value="小強">小強</option>
  </select>
  </td>
 </tr>
 <tr>
  <td>內容:</td>
  <td><textarea name="content" cols="30" rows="5" 
    ng-model="ctrl.content" required></textarea></td>
 </tr>
 <tr>
  <td>&nbsp;</td>
  <td>
   <input type="submit" name="submit" value="送出" 
     ng-disabled="myForm.$invalid" />
      <input type="button" value="查詢Web Service" 
        ng-click="ctrl.queryRecords()">
  </td>
 </tr>
</table> 
</form>
<br />
<table class="table-striped" style="width:50%" ng-show="ctrl.showRecord">
 <thead>
  <tr>
   <th width="15%">上傳日期</th>
   <th width="20%">標題</th>
   <th width="10%">作者</th>
   <th width="99%">內容</th>
  </tr>
 </thead>
 <tbody>
  <tr ng-repeat="r in ctrl.records">
   <td><span ng-bind="r.uploaddate"></span></td>
   <td><span ng-bind="r.title"></span></td>
   <td><span ng-bind="r.author"></span></td>
   <td><span ng-bind="r.content"></span></td>
  </tr>
 </tbody> 
</table>
</body>
</html>

在這邊主要有幾個要注意的地方

1. 送出鈕

當您登打相關的欄位之後,配合AngularJS所設定的required,送出鈕才會亮起供您送出

在此透過AngularJS做POST,此時在後端的Servlet所接收到的為一JSON格式的stream,無法

使用getParameter來取得資料,網路上有相關AngularJS POST得討論喔! 在此就以AngularJS

default來實作。

Servlet code

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
  // TODO Auto-generated method stub
  RecordInformationsProxy service = new RecordInformationsProxy();
  BufferedReader reader = request.getReader();
  try{
   String input = reader.readLine();
   JSONObject requestData = JSONObject.fromObject(input);
   System.out.println("==>"+requestData);
   String uploadid = UUID.randomUUID().toString();
   String title    = requestData.getString("title");
   String author   = requestData.getString("author");
   String content  = requestData.getString("content");
   System.out.println(title+","+author+","+content);
   System.out.println("Upload ID:"+uploadid);
   String returnMsg = service.uploadRecord(uploadid, composeXML(title, author, content));
   
   response.getWriter().print(returnMsg);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   reader.close();
  }
 }

public String composeXML(String ...params){
  String xmltag[] = {"title", "author", "content"};
  XMLOutputter fmt = new XMLOutputter();
  Format format = Format.getPrettyFormat();
  Element root = new Element("document");
  Element record = new Element("records");
  Element tag = null;
  Document xmldoc = new Document(root);
  root.addContent(record);
  
  for(int i = 0 ; i < params.length ; i++){
   tag = new Element(xmltag[i]);
   record.addContent(tag);
   tag.addContent(params[i]);
  }
  
  fmt.setFormat(format.setEncoding("UTF-8"));
  System.out.println(fmt.outputString(xmldoc));
  
  return fmt.outputString(xmldoc);
 }

2. 查詢Web Service鈕

主要是將Web Service內所記錄的資料進行查詢,此資料是儲存在記憶體之中,純粹得知目

前傳送多少筆資料。

Servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  response.setCharacterEncoding("UTF-8");
  RecordInformationsProxy service = new RecordInformationsProxy();
  String records = service.showRecord();
  response.getWriter().print(records);
 }

DEMO




補充

Web Service用到的library

JSON
json-lib-2.0-jdk15.jar
commons-beanutils-1.7.jar
commons-collections-3.1.jar
commons-lang-2.3.jar
commons-logging-1.0.2.jar
ezmorph-1.0.3.jar

XML
jdom.jar

建置Web Service產生
commons-discovery-0.2.jar
commons-logging.jar
axis.jar
jaxrpc.jar
saaj.jar
wsdl4j.jar

Web Service Client用到的library
同上

留言