【问题标题】:Spring Boot 2.0.0.M4 and email address as @PathVariable gives HTTP 500 errorSpring Boot 2.0.0.M4 和@PathVariable 的电子邮件地址给出了 HTTP 500 错误
【发布时间】:2018-03-18 06:33:49
【问题描述】:

我正在尝试从 Spring Boot 1.5.7 迁移到 2.0.0.M4

这是我的休息控制器:

@RestController
@RequestMapping("/v1.0/users")
public class UsersController {

    @Autowired
    private UserService userService;


    @RequestMapping(value = "/validate-username/{username}", method = RequestMethod.GET)
    @ResponseStatus(value = HttpStatus.OK)
    public void validateUsername(@PathVariable String username) {
        throw new EntityAlreadyExistsException();
    }

...

}

这是异常处理程序:

@ControllerAdvice
public class GlobalControllerExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.CONFLICT)
    public Map<String, ResponseError> handleEntityAlreadyExistsException(EntityAlreadyExistsException e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.debug("API error", e);
        return createResponseError(HttpStatus.CONFLICT.value(), e.getMessage());
    }

}

在以下用户名的情况下,例如:alex 一切正常,我收到409 状态代码,application/json; charset=UTF-8 作为内容类型,但在以下用户名的情况下,例如, alex@test.com 我的端点返回 500 状态码和非 JSON 内容类型,如下所示:

当用户名 PathVariable 最后包含 .com 时,我可以重现此问题。

我使用嵌入式 Tomcat 作为应用服务器。与 Spring Boot 1.5.7 相同的功能运行良好。如何使其与 Spring Boot 2.0.0.M4 一起使用?

附言

我知道将电子邮件地址作为 URL 参数发送是一种不好的做法。我只是对这个特殊案例感兴趣。

【问题讨论】:

  • 这确实是一个非常有趣的案例。我正在研究它,并会在找到解决方案(或解释)后立即发布
  • @geoand 谢谢,非常感谢您在这个问题上的帮助
  • 我已经确定了问题的确切原因,我正在寻找适当的解决方法:)
  • 太好了,期待您的修复!
  • @alexanoid 解决方案现在正在回答中

标签: spring-mvc tomcat spring-boot spring-restcontroller


【解决方案1】:

试试这个朋友,{username:.+},而不是你的{username}

编辑:我发现 @ 是 URL 的保留字符,不应在 URL 中使用。您需要对您的 URL 进行编码。

类似:alex@test.com -> alex%40test.com

来源:Another stackoverflow question

【讨论】:

  • 您尝试输入produces = MediaType.APPLICATION_JSON_VALUE 吗?
  • 这样会产生以下错误 - TTP Status 406 – Not Acceptable Type Status Report Description The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.
  • 用@Pathvariable(name="username") 尝试我的第一个建议,不会有什么坏处:P。另请查看我的小型研究
  • 不幸的是,即使使用 URLEncoder.encode(EMAIL, "UTF-8") 仍然无法正常工作
  • 不,我认为您需要将已编码的电子邮件发送到该 RestController,然后对其进行解码。
【解决方案2】:

您观察到的问题深入到 Spring WebMvc 内部。

根本原因是 Spring 正在推测接受的响应类型。 具体来说,在alex@test.com 的情况下,实际为接受的响应类型提供答案的策略类是ServletPathExtensionContentNegotiationStrategy,它根据路径中的发现进行猜测。

由于com 是一个有效的文件扩展类型(参见this),Spring Boot 2.0.0.M4 尝试使用该 mime 类型将您的响应从您的 ControllerAdvice 类转换为该 mime类型(当然失败),因此回退到它的默认错误响应。

解决此问题的第一个方法是指定 HTTP 标头 Accept 和一个值 的application/json。

不幸的是 Spring 2.0.0.M4 仍然不会使用这种 mime 类型,因为 ServletPathExtensionContentNegotiationStrategy 策略优先于HeaderContentNegotiationStrategy。

此外,使用了alex 或者(甚至类似alex@test.gr 之类的东西),Spring 没有猜到任何 mime 类型,因此允许常规流程继续进行。

这个工作的原因是 Spring Boot 1.5.7.RELEASE 是 Spring 没有尝试将 com 映射到 mime 类型,因此使用默认响应类型,它允许将响应对象转换为 JSON 的过程继续。

两个版本的区别归结为this和this。

现在是更有趣的部分,当然是修复。 我想到了两个解决方案,但我只会展示第一个,而只提及第二个。

这是基于我对问题的解释的第一个解决方案。 我承认这个解决方案确实有点侵入性,但它就像一个魅力。

我们需要做的是更改自动配置的ContentNegotiationManager,以便用我们自己的自定义PathExtensionContentNegotiationStrategy 替换提供的PathExtensionContentNegotiationStrategy。这样的操作很容易被BeanPostProcessor执行。

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.PathExtensionContentNegotiationStrategy;
import org.springframework.web.context.request.NativeWebRequest;

import java.util.ListIterator;

@Configuration
public class ContentNegotiationManagerConfiguration {

    @Bean
    public ContentNegotiationManagerBeanPostProcessor contentNegotiationManagerBeanPostProcessor() {
        return new ContentNegotiationManagerBeanPostProcessor();
    }


    private static class ContentNegotiationManagerBeanPostProcessor implements BeanPostProcessor {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            return bean; //no op
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (!(bean instanceof ContentNegotiationManager)) {
                return bean;
            }

            final ContentNegotiationManager contentNegotiationManager = (ContentNegotiationManager) bean;

            ListIterator<ContentNegotiationStrategy> iterator =
                    contentNegotiationManager.getStrategies().listIterator();

            while (iterator.hasNext()) {
                ContentNegotiationStrategy strategy = iterator.next();
                if (strategy.getClass().getName().contains("OptionalPathExtensionContentNegotiationStrategy")) {
                    iterator.set(new RemoveHandleNoMatchContentNegotiationStrategy());
                }
            }

            return bean;
        }
    }

    private static class RemoveHandleNoMatchContentNegotiationStrategy
            extends PathExtensionContentNegotiationStrategy {

        /**
         * Don't lookup file extensions to match mime-type
         * Effectively reverts to Spring Boot 1.5.7 behavior
         */
        @Override
        protected MediaType handleNoMatch(NativeWebRequest request, String key) {
            return null;
        }
    }
}

可以实现的第二种解决方案是利用 Spring 默认使用的 OptionalPathExtensionContentNegotiationStrategy 类的功能。

基本上你需要做的是确保对validateUsername端点的每个HTTP请求都包含一个名为org.springframework.web.accept.PathExtensionContentNegotiationStrategy.SKIP的属性,其值为true

【讨论】:

  • 非常感谢您的详细解答!!
【解决方案3】:

This article 展示了如何阻止 Spring 使用路径扩展进行内容协商(至少在 Spring Boot 1.5.x 中对我有用):

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override 
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { 
        configurer.favorPathExtension(false); 
    }
}

【讨论】:

    【解决方案4】:

    一种最短的解决方案是修改您的网址,如下所示

    @RequestMapping(value = "/validate-username/{username}/"
    

    注意:我在 URL 的末尾使用斜杠 '/'。因此,该 URL 将完美地适用于任何类型的电子邮件地址或 .com , .us,在您的 {username} 路径变量中包含文本。 您无需向应用程序添加任何类型的额外配置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 2018-03-16
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 2018-03-15
      相关资源
      最近更新 更多