Spring MVC中的可选POST参数?
问题内容:
我有以下代码:
@RequestMapping(method = RequestMethod.POST)
public ModelAndView editItem(String name, String description)
但是,有时不传递描述(这是一个比实际示例简化的示例),我想使描述成为可选的,如果没有传递,则可能填写默认值。
有人知道该怎么做吗?
非常感谢!
杰森
问题答案:
代替使用@RequestParam
可选参数,使用type的参数org.springframework.web.context.request.WebRequest
。例如,
@RequestMapping(method = RequestMethod.POST)
public ModelAndView editItem(
@RequestParam("name")String name,
org.springframework.web.context.request.WebRequest webRequest)
{
String description = webRequest.getParameter("description");
if (description != null)
{
// optional parameter is present
}
else
{
// optional parameter is not there.
}
}
注意:请参见下面的内容(defaultValue和required),以解决不使用WebRequest参数的情况。