Spring中的@RequestParam如何处理Guava的Optional?

2024-04-17

@RequestMapping(value = "/contact.html", method = RequestMethod.POST)
public final ModelAndView contact(
        @RequestParam(value = "name", required = false) Optional<String> name) {

春天的情况如何@RequestMapping处理一个Optional https://google.github.io/guava/releases/23.0/api/docs/com/google/common/base/Optional.html from 番石榴库 https://code.google.com/p/guava-libraries/如果不需要参数值并且不发送任何内容?

那将会:

  • Set to null
  • Set to Optional.absent()

Can Optional.fromNullable(T)用于接受请求?


编辑(2015 年 10 月):弹簧4手柄java.util.Optional(从 Java 8 开始)开箱即用并且保证Optional其本身不为空,但最初的问题是关于番石榴的com.google.common.base.Optional其用法为@RequestParam在这种特定情况下非常不鼓励(因为它can为空)。

原答案(关于番石榴的Optional):

不要这样做,只需使用String并让 Spring 处理null以它的方式。

Optional<T>应该用作返回值 https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained#whats-the-point并且很少作为参数。在这种特殊情况下,Spring 将映射缺失的"name"参数为null,所以即使在实施自定义之后属性编辑器 http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html#beans-beans-conversion-customeditor-registration你会完成null check:

@RequestMapping("foo")
@ResponseBody
public String foo(@RequestParam(required = false) final Optional name) {
  return "name: " + (name == null ? "null" : name.get());
}

这是完全没有必要的(并且误用Optional),因为它可以通过以下方式实现:

@RequestMapping("foo")
@ResponseBody
public String foo(@RequestParam(required = false) final String name) {
  return "name: " + (name == null ? "null" : name);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring中的@RequestParam如何处理Guava的Optional? 的相关文章

随机推荐