簡體   English   中英

為Java / Spring RESTful服務創建客戶端

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

我已經開發了Java/Spring RESTful服務,該服務在cURL請求上返回JSON 例如,如果我提供cURL請求,例如,

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

我收到了請求的回復,

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

我的代碼在

@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 

}

提供了項目結構,

在此處輸入圖片說明

我需要使用Ajax請求為RESTful開發客戶端。 例如,在前端提供的代碼會創建一個下拉菜單,其中包含如下所示的錢包信息(name+space+address)

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

我在教程中看到了一個示例,但是,在創建HTML頁面之后,我需要知道是否需要編寫一個控制器來調用它或執行什么操作? 例如

@Controller
public class MyClass{

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

帶有Ajax請求的一些示例代碼片段將幫助我入門。 怎么做?

這是使用ajax的代碼示例。 它顯示了如何調用您的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正如您在評論中要求的完整html示例一樣,所以我給您一個想法。 我沒有關於您的下拉菜單的任何信息。

更新:

 <!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> 

使用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