簡體   English   中英

用Java硬編碼@PathVariable

[英]Hard coding @PathVariable in Java

我是Java的新手,仍然想圍繞它的許多概念來思考。

現在在我的應用程序中,該應用程序從外部api提取數據。 我目前正在嘗試對路徑進行硬編碼,以確保得到期望的響應(這是一個臨時交互,最終,我希望應用程序是無狀態的。如果我在@PathVariable中傳遞硬編碼值我的代碼上面定義了變量的控制器無法讀取該值。

我應該在哪里放置硬編碼的值,我是否以正確的方式定義它?

碼:

String identificationCode ="abcd";
@RequestMapping(value ="/download/{identificationCode}", method = RequestMethod.GET)
String downloadDocument(@PathVariable(value="identificationCode") String identificationCode) {
     .
     .
     .
}

value是名稱的別名。 這意味着@PathVariable(value="identificationCode")指定此參數的變量名稱,而不是value。 看到

此處為"/download/{identificationCode}"

identificationCode不會通過在此處聲明的String的值進行插值:

String identificationCode ="abcd";

它將僅生成字符串: "/download/{identificationCode}"

你可以這樣寫:

@RequestMapping(value ="/download/"+identificationCode, method = RequestMethod.GET)

但是它也不起作用,因為identificationCode不是常量表達式。

所以,您想要的只是:

@RequestMapping(value ="/download/abc", method = RequestMethod.GET)

如果您不需要在其他地方引用String,請使用這種方式。

否則,可以將identificationCode聲明為常量表達式(並且您也可以通過static方式進行此操作):

final static String identificationCode ="abcd";

您可以這樣使用它:

@RequestMapping(value ="/download/"+identificationCode, method = RequestMethod.GET)

將{identificationCode}替換為@RequestMapping(value =“ / download / {identificationCode}”“中的硬編碼值。稍后,當您需要路徑的動態性質時,可以按照當前編碼的方式進行操作。

暫無
暫無

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

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