简体   繁体   English

为Java / Spring RESTful服务创建客户端

[英]Creating the client for the Java/Spring RESTful service

I have developed Java/Spring RESTful service that returns JSON on the cURL requests. 我已经开发了Java/Spring RESTful服务,该服务在cURL请求上返回JSON For example, if I provide cURL request eg, 例如,如果我提供cURL请求,例如,

curl -G http://localhost:8080/rest/wallets | json

I get the response of the request, 我收到了请求的回复,

[
  {
    "name": "Puut",
    "address": "mv7eLe6vva4SJ96tZiczd1XPYiUxgUudAX"
  },
  {
    "name": "Rool",
    "address": "n4W2zC6WE98SAAnKEJoatvELnbiLeVFZFf"
  },
  {
    "name": "Ouup",
    "address": "mj5DZbgngdK2Wnz4Q7Gv2UGYRyGSYnuhG6"
  }
]

I have the code in the 我的代码在

@RestController
@RequestMapping("/rest")
public class WalletRestController {

    @Autowired
    private WalletService walletService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/wallets", method = RequestMethod.GET)
    public ResponseEntity<List<WalletInfoWrapper>> getAllWalletInfo() {

        List<WalletInfo> walletInfos = walletService.getAllWallets();

        if (Objects.isNull(walletInfos)) {
            return new ResponseEntity<List<WalletInfoWrapper>>(HttpStatus.NO_CONTENT);
        }

        List<WalletInfoWrapper> walletInfoWrappers = new ArrayList<>();

        // hiding the entity ids for the security purposes
        walletInfos.forEach(w -> walletInfoWrappers.add(new WalletInfoWrapper(w.getName(), w.getAddress())));

        return new ResponseEntity<List<WalletInfoWrapper>>(walletInfoWrappers, HttpStatus.OK);
    }

    // some code 

}

The project structure is provided, 提供了项目结构,

在此处输入图片说明

I need to develop a client for the RESTful with Ajax requests. 我需要使用Ajax请求为RESTful开发客户端。 For example, the code provided, say, in the front-end, it creates a drop-down menu with the wallets info (name+space+address) like this, 例如,在前端提供的代码会创建一个下拉菜单,其中包含如下所示的钱包信息(name+space+address)

|----------------------------------------|
|Puut  mv7eLe6vva4SJ96tZiczd1XPYiUxgUudAX|
|----------------------------------------|
|Rool  n4W2zC6WE98SAAnKEJoatvELnbiLeVFZFf|
|----------------------------------------|
|Ouup  mj5DZbgngdK2Wnz4Q7Gv2UGYRyGSYnuhG6|
|----------------------------------------|

I see an example in the tutorial , however, I need to know after creating the HTML page, do I need to write a controller to call it or what? 我在教程中看到了一个示例,但是,在创建HTML页面之后,我需要知道是否需要编写一个控制器来调用它或执行什么操作? eg 例如

@Controller
public class MyClass{

      @RequestMapping(value = "/", method= RequestMethod.GET)
      public String showHome(){
            retrurn "home.html";
      }
}

Some sample code snippet with Ajax requests will help me to get started. 带有Ajax请求的一些示例代码片段将帮助我入门。 How to do that? 怎么做?

This is the code sample using ajax. 这是使用ajax的代码示例。 It shows how to call your rest controller.port can by vary depending on your config.but usually tomcat uses 8080 port. 它显示了如何调用您的rest controller.port可以根据您的配置而有所不同。但是tomcat通常使用8080端口。

<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
$.ajax({
    type: 'GET',
    url: 'http://localhost:8080/rest/wallets',
    data: '',
    success: function (responseData) {

            console.log(JSON.stringify(responseData));
    },
    complete: function (textStatus) {

    },
    error: function (responseData)
    {
    }
});

@Artin As you asked in the comment for complete html example so I give you an idea. @Artin正如您在评论中要求的完整html示例一样,所以我给您一个想法。 I don't have any information about your drop down. 我没有关于您的下拉菜单的任何信息。

Update: 更新:

 <!DOCTYPE html> <html> <head> <title>Rest Service Calling example</title> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <script type="text/javascript"> function getData(){ $.ajax({ type: 'GET', /*If you need some basic authentication then you need to include it also. 'Access-Control-Allow-Origin' is for CORS issue*/ /*headers:{ "Authorization": "Basic *********", 'Access-Control-Allow-Origin':'*' },*/ url: 'http://localhost:8080/rest/wallets', /*Since you don't send any data, so data will be empty*/ data: '', success: function (responseData) { console.log(JSON.stringify(responseData)); $('#result').html(JSON.stringify(responseData)) }, complete: function (textStatus) { }, error: function (responseData) { } }); } </script> <style> </style> </head> <body> <p>Data From Server : </p> <div id="result" ></div> <input type="button" value="Get Data" onclick="getData()"> </body> </html> 

Using JQuery: 使用JQuery:

$.ajax({
   url: 'wallets',
   data: 'myAnyParameterIfNeeded=parameterValue',
   success : function(response) {
                var results = JSON.parse(response);
                // here you can use for loop for iterating into *results*
                var rowOneName = JSON.stringify(results[0]['name']);
           }
   error : function(e){
               alert('HTTP error number=' + e.status);
           }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM