簡體   English   中英

如何使用Spring正確管理PathVariables

[英]How to properly manage PathVariables with spring

我希望這不是一個簡單的問題。 我是Java Web服務世界的新手,似乎無法在控制器中訪問PathVariables。 我正在使用STS,並且沒有抱怨我的語法錯誤。

比正確答案重要得多,我真的很想知道為什么這不起作用。

這是一些我無法使用的示例代碼:

@RestController
public class TestController {

    @RequestMapping("/example")
    public String doAThing(
        @PathVariable String test
    ) throws MessagingException {
        return "Your variable is " + test;
    }
}

如果我像這樣卷曲一下:

curl http://localhost:8080/example?test=foo

我收到以下答復:

{“時間戳”:1452414817725,“狀態”:500,“錯誤”:“內部服務器錯誤”,“例外”:“ org.springframework.web.bind.MissingPathVariableException”,“消息”:“缺少URI模板變量'test '用於類型為String“,” path“:” / example“}的方法參數

我知道我已正確連接了其他所有設備,其他控制器也正常工作。

我覺得我這里一定缺少一些基本原理。

提前致謝。

如果使用路徑變量,則它必須是URI的一部分。 正如您沒有在URI中提到的那樣,而是在方法參數中使用的,spring嘗試從路徑URI中找出並分配該值。 但是此路徑變量不在路徑URI中,因此拋出MissingPathVariableException。

這應該工作。

@RestController
public class TestController {

@RequestMapping("/example/{test}")
public String doAThing(
    @PathVariable String test
) throws MessagingException {
    return "Your variable is " + test;
}
}

而你的卷曲要求就像

curl http://localhost:8080/example/foo
//here the foo can be replace with other string values

Spring支持通過不同方式將內容從url映射到方法參數的各種方法:請求參數和路徑變量

  • 請求參數取自url查詢參數(和請求正文,例如在http-POST請求中)。 標記應從請求參數獲取其值的java方法參數的注釋為@RequestParam

  • 路徑變量(有時稱為路徑模板)是url路徑的一部分。 標記應從請求參數獲取其值的java方法參數的注釋為@PathVariable

看一下我的這個答案 ,例如一個到Spring Reference的鏈接。

因此,您的問題是:您想讀取一個請求參數(從url查詢部分),但是對路徑變量使用了注釋。 因此,您必須使用@RequestParam而不是@PathVariable

@RestController
public class TestController {

    @RequestMapping("/example")
    public String doAThing(@RequestParam("test") String test) throws MessagingException {
        return "Your variable is " + test;
    }
}

它不起作用的原因是,有兩種方法可以使用RestController將參數傳遞給REST API實現。 一個是PathVariable,另一個是RequestParam。 兩者都需要在RequestMapping批注中指定名稱。

查看這個出色的資源,它詳細解釋了RequestMapping

嘗試此解決方案。

@RequestMapping("/example/{test}", method= RequestMethod.GET)
public String doAThing(
    @PathVariable("test") String test
) throws MessagingException {
    return "Your variable is " + test;
}

我的解決方案是:

@RestController
@RequestMapping("/products")
@EnableTransactionManagement
public class ProductController {
    @RequestMapping(method = RequestMethod.POST)
    public Product save(@RequestBody Product product) {
        Product result = productService.save(product);
        return result;
    }
}

暫無
暫無

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

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