簡體   English   中英

使用 Spring ZC6E190B284633C48E39E55049ZD1Z 將自定義 object 從客戶端傳遞到 REST 端點

[英]Passing custom object from client to REST endpoint using Spring Web

我正在制作一個客戶端-服務器應用程序,它將矩陣發送到服務器,在服務器上計算其行列式,然后發送回客戶端。 我制作了這個包裝器 class:

public class MatrixDTO { // with getters and setters
    private double[][] matrix;
    private double determinant;
}

而且我還實現了從 MatrixDTO object 獲取行列式的服務器邏輯。 我在服務器中添加了這個 RestController:

@RestController
public class MatrixController {
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public MatrixDTO postMapping(@RequestParam MatrixDTO matrixDTO) {
        // code to compute determinant ommitted
        matrixDTO.setDeterminant(determinant);
        return matrixDTO;
    }

然后在客戶端中,我添加了這種發送請求的方法:

final String uri = "http://localhost:8080/?matrixDTO={matrixDTOparam}";
// initialized wrapper object only with matrix data
MatrixDTO input = new MatrixDTO(data);
Map<String, MatrixDTO> params = new HashMap<>();
params.put("matrixDTOparam", input);

RestTemplate restTemplate = new RestTemplate();

result = restTemplate.postForObject(uri, input, MatrixDTO.class, params);
// now I should be able to extract the determinant with result.getDeterminant()

為了讓這個簡單的代碼工作,我們浪費了很多時間。 錯誤是:

Failed to convert value of type 'java.lang.String' to required type 'MatrixDTO'; 
nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'MatrixDTO': 
no matching editors or conversion strategy found]

我的問題如下:我應該為我的問題選擇另一種方法嗎?如果沒有,是否有一種簡單的方法可以使代碼正常工作? 我正在尋找一個簡單的實現,而不是做很多配置。 謝謝。

到目前為止,我的錯誤似乎是在 controller 中使用 @RequestParam 而不是 @RequestBody。 通過更改它並在客戶端中使用此代碼:

final String uri = "http://localhost:8080/";
MatrixDTO input = new MatrixDTO(data);

RestTemplate restTemplate = new RestTemplate();
result = restTemplate.postForObject(uri, input, MatrixDTO.class);

它似乎工作得很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM