How to invoke a REST service

六月ゝ 毕业季﹏ 提交于 2019-12-31 07:46:08

问题


I have created a REST service which retrieves data from the database as per the request made and returns it JSON format.

Now, I need to create a HTML page with a button that, when clicked, should get the appropriate data from the service. I have learnt that this can be done through ajax. But am not aware how to do it.

The service uses Spring Framework and Apache CXF and retrieves data from a Mysql database, if that matters.

Code i have added to create my client:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

      <script type="text/javascript">
         $(document).ready(function() {
            $("#driver").click(function(event){
               $.getJSON('http://localhost:8080/CxfRestService/rest/employeeservices/getList');
               });
            });
         });
      </script>

   </head>

   <body>

      <input type="button" id="driver" value="Get Employee Data" />

   </body>

Do i need to place my HTML page into my Java project and add the related configuration in my web.xml/beans.xml or something?


回答1:


Well, all your service does is respond to HTTP requests. So, you need to send one - either

  • direct the browser to move to a corresponding URL (document.location.href = <url>), or
  • send an XMLHTTPRequest (aka AJAX) and parse the result, for which JQuery has built-in functionality.
    • then edit the currently loaded page to include the results the way you like using DOM (see e.g. Google on "jquery tutorial editing DOM" for that)
    • See e.g. AJAX Introduction - W3Schools for an AJAX overview. It describes how this happens in plain JS, jquery.ajax is a convenient wrapper over that.

You don't need to connect you client-side stuff with the Java project in any way - REST is specifically designed to allow them to be independent.



来源:https://stackoverflow.com/questions/33061112/how-to-invoke-a-rest-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!