【问题标题】:Spring Controller doesnt accept url which ends with .uriSpring Controller 不接受以 .uri 结尾的 url
【发布时间】:2019-03-21 14:51:22
【问题描述】:

我已经定义了下面的控制器

@Controller

公共类 HelloController {

@RequestMapping(value = "/config/{name:.*}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.GET)
@ResponseBody
ResponseEntity<String> getValue(@PathVariable String name) {
    String value = "Hello World";
    return new ResponseEntity<String>(HttpStatus.OK);
}

}

当我从浏览器执行 ping url 时: http://localhost:8080/example/config/test.abc

请求工作正常。

但是当我用 url ping http://localhost:8080/example/config/test.uri

它只是用错误来炸毁页面: The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

我尝试了 MessageConverters 和 configureContentNegotiation 似乎没有任何工作。 我想知道 spring 是否将 test.uri 视为无效模式或保留关键字。

我尝试过的环境。 春天 4/雄猫 7 & 8 Spring 5/Tomcat 9

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    尝试不同的正则表达式。

    而不是

    .*
    

    这意味着:除了换行符之外的任意数量的任意字符

    试试

    [a-z]*\.[a-z]*
    

    这意味着 不同数量的 a-z + 一个点 + 不同数量的 a-z

    如果这是你想要的。

    如果你不需要任何模式,那么就使用

    {name}
    

    结帐

    https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/uri-pattern.html

    https://regexr.com/

    但我会考虑您是否可以调整您的 API,例如:

    @RequestMapping(value = "/config/{name}/{type}", ...
    

    我认为在 URI 中期望点不是一个好主意。 点表示您正在请求文件。

    结帐:

    Spring MVC @PathVariable with dot (.) is getting truncated

    【讨论】:

    • 能否请您添加解释为什么 test.test, test.url 工作但 test.uri 不工作?在答案中
    • 我试过 {name} 和 [a-z]*\.[a-z]* 运气不佳。我不能采用 @RequestMapping(value = "/config/{name}/{type}" 的模式,因为这对我们来说是一个非常大的变化
    • 然后可以尝试 /somepath/{variable:.+} ,如我上一个链接中所述
    【解决方案2】:

    Spring 认为最后一个点后面的任何内容都是文件扩展名

    克服这个问题

    通过添加正则表达式映射修改我们的@PathVariable 定义

    @RequestMapping(value = "/config/{name:.+}"
    

    一个安全的猜测是

    .abc 没有扩展类型,.uri 是一个扩展,所以也许这就是你的第一个 URL 有效的原因,

    【讨论】:

      【解决方案3】:

      我终于可以使用 ContentNegotiationConfigurer 解决问题并为 uri 设置内容类型。

          @Override
      public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer) {
          contentNegotiationConfigurer.mediaType("uri", MediaType.TEXT_PLAIN);
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-10
        • 1970-01-01
        • 2018-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 2017-05-06
        • 1970-01-01
        相关资源
        最近更新 更多