繁体   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