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如下:

  1. public String uploadRecord(String uploadid, String xmlcontent){
  2. String returnMsg = "upload data success!!";
  3. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  4. SAXBuilder builder = new SAXBuilder();
  5. if(processRecords == null)processRecords = new ArrayList<Record>();
  6. try {
  7. Document document = (Document) builder.build(
  8. new ByteArrayInputStream(xmlcontent.getBytes("utf-8")));
  9. Element rootNode = document.getRootElement();
  10. List<?> list = rootNode.getChildren("records");
  11. if(list.size() > 0){
  12. Element node = (Element) list.get(0);
  13. System.out.println("title : " + node.getChildText("title"));
  14. System.out.println("author : " + node.getChildText("author"));
  15. System.out.println("content : " + node.getChildText("content"));
  16. Record bean = new Record(uploadid);
  17. bean.setAuthor(node.getChildText("author"));
  18. bean.setContent(node.getChildText("content"));
  19. bean.setTitle(node.getChildText("title"));
  20. bean.setUploaddate(sdf.format(
  21. new java.sql.Date(System.currentTimeMillis())));
  22. processRecords.add(bean);
  23. }else{
  24. returnMsg = "upload data format error!!";
  25. }
  26. } catch (JDOMException | IOException e) {
  27. // TODO Auto-generated catch block
  28. e.printStackTrace();
  29. }
  30. return returnMsg;
  31. }

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

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

private static List<Record> processRecords;

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

  1. public String showRecord(){
  2. JSONArray records = new JSONArray();
  3. if(processRecords != null){
  4. Iterator<Record> list = processRecords.iterator();
  5. while(list.hasNext()) {
  6. Record record = list.next();
  7. JSONObject data = new JSONObject();
  8. data.put("uploaddate", record.getUploaddate());
  9. data.put("title", record.getTitle());
  10. data.put("author", record.getAuthor());
  11. data.put("content", record.getContent());
  12. records.add(data);
  13. }
  14. System.out.println("==>"+records.toString());
  15. return records.toString();
  16. }else{
  17. return "nodata";
  18. }
  19. }

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

  1. <html ng-app="recordApp">
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>Test Record Web Service</title>
  5. <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
  6. <script src="js/angular.js"></script>
  7. <script src="js/jquery-2.1.3.js"></script>
  8. <script src="js/bootstrap.min.js"></script>
  9. <script type="text/javascript">
  10. angular.module('recordApp', [])
  11. .controller('MainCtrl', ['$http', function($http){
  12. var self = this;
  13. self.records = [];
  14. self.showRecord = false;
  15. self.queryRecords = function(){
  16. $http.get('/WebServiceTest/QueryRecordService'
  17. ).then(function(response){
  18. if(response.data == 'nodata'){
  19. alert("目前無任何資料!!");
  20. }else{
  21. self.showRecord = true;
  22. self.records = response.data;
  23. }
  24. }, function(errResponse){
  25. alert('連接Web Service出錯!');
  26. });
  27. };
  28. self.submitRecord = function(){
  29. $http.post('/WebServiceTest/ConnectRecordService',
  30. {title:self.title,
  31. author:self.selectAuthor,
  32. content:self.content}
  33. ).then(function(response){
  34. alert(response.data);
  35. }, function(response){
  36. alert("failed!!");
  37. });
  38. };
  39. }]);
  40. </script>
  41. </head>
  42. <body ng-controller="MainCtrl as ctrl">
  43. <form name="myForm" ng-submit="ctrl.submitRecord()">
  44. <table class="table" style="width:30%">
  45. <tr>
  46. <td>標題:</td>
  47. <td><input type="text" name="title" size="30"
  48. ng-model="ctrl.title" required /></td>
  49. </tr>
  50. <tr>
  51. <td>作者:</td>
  52. <td>
  53. <select ng-model="ctrl.selectAuthor" required>
  54. <option value="小彬">小彬</option>
  55. <option value="小美">小美</option>
  56. <option value="小強">小強</option>
  57. </select>
  58. </td>
  59. </tr>
  60. <tr>
  61. <td>內容:</td>
  62. <td><textarea name="content" cols="30" rows="5"
  63. ng-model="ctrl.content" required></textarea></td>
  64. </tr>
  65. <tr>
  66. <td>&nbsp;</td>
  67. <td>
  68. <input type="submit" name="submit" value="送出"
  69. ng-disabled="myForm.$invalid" />
  70. <input type="button" value="查詢Web Service"
  71. ng-click="ctrl.queryRecords()">
  72. </td>
  73. </tr>
  74. </table>
  75. </form>
  76. <br />
  77. <table class="table-striped" style="width:50%" ng-show="ctrl.showRecord">
  78. <thead>
  79. <tr>
  80. <th width="15%">上傳日期</th>
  81. <th width="20%">標題</th>
  82. <th width="10%">作者</th>
  83. <th width="99%">內容</th>
  84. </tr>
  85. </thead>
  86. <tbody>
  87. <tr ng-repeat="r in ctrl.records">
  88. <td><span ng-bind="r.uploaddate"></span></td>
  89. <td><span ng-bind="r.title"></span></td>
  90. <td><span ng-bind="r.author"></span></td>
  91. <td><span ng-bind="r.content"></span></td>
  92. </tr>
  93. </tbody>
  94. </table>
  95. </body>
  96. </html>

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

1. 送出鈕

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

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

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

default來實作。

Servlet code

  1. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
  2. // TODO Auto-generated method stub
  3. RecordInformationsProxy service = new RecordInformationsProxy();
  4. BufferedReader reader = request.getReader();
  5. try{
  6. String input = reader.readLine();
  7. JSONObject requestData = JSONObject.fromObject(input);
  8. System.out.println("==>"+requestData);
  9. String uploadid = UUID.randomUUID().toString();
  10. String title = requestData.getString("title");
  11. String author = requestData.getString("author");
  12. String content = requestData.getString("content");
  13. System.out.println(title+","+author+","+content);
  14. System.out.println("Upload ID:"+uploadid);
  15. String returnMsg = service.uploadRecord(uploadid, composeXML(title, author, content));
  16. response.getWriter().print(returnMsg);
  17. }catch(Exception e){
  18. e.printStackTrace();
  19. }finally{
  20. reader.close();
  21. }
  22. }
  23. public String composeXML(String ...params){
  24. String xmltag[] = {"title", "author", "content"};
  25. XMLOutputter fmt = new XMLOutputter();
  26. Format format = Format.getPrettyFormat();
  27. Element root = new Element("document");
  28. Element record = new Element("records");
  29. Element tag = null;
  30. Document xmldoc = new Document(root);
  31. root.addContent(record);
  32. for(int i = 0 ; i < params.length ; i++){
  33. tag = new Element(xmltag[i]);
  34. record.addContent(tag);
  35. tag.addContent(params[i]);
  36. }
  37. fmt.setFormat(format.setEncoding("UTF-8"));
  38. System.out.println(fmt.outputString(xmldoc));
  39. return fmt.outputString(xmldoc);
  40. }

2. 查詢Web Service鈕

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

前傳送多少筆資料。

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

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
同上

留言