3

(见下面的编辑部分 20.08.2015)

我最近遇到了类似的问题(Get request 仅适用于斜杠(spring REST annotations)),解决方案是在 @RequestMapping 的值中添加一个正则表达式(另见Spring MVC @PathVariable getting truncated)。

但现在我们意识到问题仍然存在,但仅限于以 .com 或 .org 结尾的电子邮件地址。这很奇怪。

不久,我使用 Spring Annotations 构建 REST 服务。我有一个带有三个参数的 GET 请求,最后一个是电子邮件。

我的控制器:

@RequestMapping(method = GET, value = "/{value1}/{value2}/{value3:.+}",
  produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")    
  public ResponseEntity<MyResponseType> getMyResource(
    @ApiParam(value = "...",...)
    @PathVariable("value1") String value1,
    @ApiParam(value = "...",...)
    @PathVariable("value2") String value2,
    @ApiParam(value = "...",...)
    @PathVariable("value3") String value3) {
      //...
}

如果我打电话: http://myserver:8080/myresource/value1/value2/value3

value3= email@domain.de / co.uk / .name / .biz /.info,完全没有问题。

但是对于某些顶级域(到目前为止.com、.org),我收到 Http 状态代码 406(不接受)。

如果我添加一个斜杠,它会起作用:

http://myserver:8080/myresource/value1/value2/value3/

由于我们使用 swagger 并且 swagger 不添加斜杠,因此添加斜杠不是一种选择。

什么可能导致这个问题?

我使用了一个扩展 ResponseEntityExceptionHandler 的 ErrorHandler。我调试了一下,发现抛出了HttpMediaTypeNotAcceptableException(“找不到可接受的表示”)。但我还不知道是谁在扔它以及为什么。


编辑

我发现路径http://myserver:8080/myresource/value1/value2/myemail@somewhere.com

被解释为文件,而“com”是媒体类型“application/x-msdownload”的文件扩展名,因此在 Spring 的类 ProducesRequestCondition.ProduceMediaTypeExpression 方法 matchMediaType 中的“getMediaType().isCompatibleWith(acceptedMediaType)”行失败,因为实际产生的媒体类型是“application/json;charset=UTF-8”,而不是“application/x-msdownload”。

所以问题变成了:我怎样才能让 Spring 理解,.com 不是文件扩展名?

4

2 回答 2

5

这个线程帮助了我: SpringMVC: Inconsistent mapping behavior based on url extension

显然这不是一个错误,而是一个“功能”,并且有两种不同的方法可以禁用它。我使用了注释版本:

@Configuration
@EnableWebMvc
public class RestCommonsMvcConfig extends WebMvcConfigurerAdapter {

  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false);
  }
}
于 2015-08-20T13:27:29.163 回答
0

我从 spring 3.1.2 升级到 3.2.7 时遇到了这个问题。尼娜的回答帮助了我(应该标记为答案)。但是WebMvcConfigurerAdapter我没有扩展我WebConfig的扩展WebMvcConfigurationSupport

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
      super.configureContentNegotiation(configurer);
      configurer.favorPathExtension(false).favorParameter(true);
  }
}
于 2015-09-15T15:34:27.207 回答