本文介绍了Spring中的@RequestParam如何处理Guava的Optional?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Spring的@RequestMapping如何处理 Optional " rel ="nofollow noreferrer"> Guava库,如果参数值不是必需的,什么都不会发送?

How does Spring's @RequestMapping handle an Optional from Guava library if the parameter value is not required and nothing is sent?

会是:

  • 设置为null
  • 设置为Optional.absent()
  • Set to null
  • Set to Optional.absent()

Optional.fromNullable(T)可以用来接受请求吗?

Can Optional.fromNullable(T) be used to accept the request?

推荐答案

编辑(2015年10月): Spring 4开箱即用处理java.util.Optional(来自Java 8)并提供保证Optional本身不为空,但最初的问题是番石榴的com.google.common.base.Optional在这种特定情况下强烈建议不要使用@RequestParam(因为可以为空).

EDIT (October 2015): Spring 4 handles java.util.Optional (from Java 8) out of the box and guarantees that Optional itself is not null, but original question was about Guava's com.google.common.base.Optional which usage as @RequestParam is highly discouraged in this specific case (because it can be null).

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

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

Don't do that, just use String and let Spring handle null in its way.

Optional<T>应该用作 return值 ,很少作为参数.在这种特殊情况下,Spring会将丢失的"name"参数映射到null,因此,即使在实现自定义属性编辑器,您将完成null检查:

Optional<T> is supposed to be used as return value and rarely as a parameter. In this particular case Spring will map missing "name" parameter to null, so even if after implementing custom property editor you'll finish with null check:

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

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

which is completely unnecessary (and missuses Optional), because it can be achieved with:

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

这篇关于Spring中的@RequestParam如何处理Guava的Optional?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:38