简体   繁体   English

用Java硬编码@PathVariable

[英]Hard coding @PathVariable in Java

I am new to java and am still trying to wrap around my mind around many of its concepts. 我是Java的新手,仍然想围绕它的许多概念来思考。

Right now in my application that pulls in data from an external api. 现在在我的应用程序中,该应用程序从外部api提取数据。 I am trying to hardcode a path, for now, to make sure that I am getting the response I am expecting (this is a temporary interaction as eventually, I want the app to be stateless. If I pass a hardcoded value for @PathVariable in my controller with the variable defined above the code doesn't read the value. 我目前正在尝试对路径进行硬编码,以确保得到期望的响应(这是一个临时交互,最终,我希望应用程序是无状态的。如果我在@PathVariable中传递硬编码值我的代码上面定义了变量的控制器无法读取该值。

Where should I be placing the hard-coded value and am I defining it the correct way? 我应该在哪里放置硬编码的值,我是否以正确的方式定义它?

Code: 码:

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

value is a alias for name. value是名称的别名。 That means that @PathVariable(value="identificationCode") specifies name of variable for this parameter, but not value. 这意味着@PathVariable(value="identificationCode")指定此参数的变量名称,而不是value。 See 看到

Here "/download/{identificationCode}" 此处为"/download/{identificationCode}"

identificationCode is not interpolated by the value of the String declared there : identificationCode不会通过在此处声明的String的值进行插值:

String identificationCode ="abcd";

It will just produce the String : "/download/{identificationCode}" . 它将仅生成字符串: "/download/{identificationCode}"

You could write it : 你可以这样写:

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

but it will not work either as identificationCode is not a constant expression. 但是它也不起作用,因为identificationCode不是常量表达式。

So what you want is just : 所以,您想要的只是:

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

Use this way if you don't need to reference the String somewhere else. 如果您不需要在其他地方引用String,请使用这种方式。

Otherwise as alternative declare identificationCode as a constant expression (and you can also do this static by the way) : 否则,可以将identificationCode声明为常量表达式(并且您也可以通过static方式进行此操作):

final static String identificationCode ="abcd";

And you could so use it : 您可以这样使用它:

@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