【问题标题】:Hard coding @PathVariable in JavaJava中的硬编码@PathVariable
【发布时间】:2018-07-27 10:08:55
【问题描述】:

我是 Java 新手,但我仍在努力思考它的许多概念。

现在在我的应用程序中,它从外部 api 中提取数据。我现在正在尝试硬编码一条路径,以确保我得到我期望的响应(这是一个临时的交互,因为最终我希望应用程序是无状态的。如果我为@PathVariable 传递一个硬编码值我的控制器与上面代码定义的变量不读取值。

我应该将硬编码值放在哪里,我是否以正确的方式定义它?

代码:

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

【问题讨论】:

  • 你这里不是把服务器和客户端搞混了吗?

标签: java spring spring-boot model-view-controller path-variables


【解决方案1】:

value 是名称的别名。这意味着@PathVariable(value="identificationCode") 指定此参数的变量名称,但不指定值。 See

【讨论】:

    【解决方案2】:

    这里"/download/{identificationCode}"

    identificationCode 没有被那里声明的字符串的值插值:

    String identificationCode ="abcd";
    

    它只会产生字符串:"/download/{identificationCode}"

    你可以写:

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

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

    所以你想要的只是:

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

    如果您不需要在其他地方引用字符串,请使用这种方式。

    否则,将identificationCode 声明为常量表达式(顺便说一下,您也可以这样做static):

    final static String identificationCode ="abcd";
    

    你可以这样使用它:

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

    【讨论】:

      【解决方案3】:

      将 {identificationCode} 替换为您在 @RequestMapping(value ="/download/{identificationCode}" 中的硬编码值。稍后,当您想要路径的动态特性时,您可以按照您当前的编码进行。

      【讨论】:

        猜你喜欢
        • 2018-10-30
        • 2015-04-30
        • 2014-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-06
        • 2012-10-17
        相关资源
        最近更新 更多