Java Spring-如何处理缺少的必需请求参数 [英] Java Spring - how to handle missing required request parameters
问题描述
请考虑以下映射:
@RequestMapping(value = "/superDuperPage", method = RequestMethod.GET)
public String superDuperPage(@RequestParam(value = "someParameter", required = true) String parameter)
{
return "somePage";
}
我想通过不添加required = false
来处理参数丢失的情况.默认情况下,返回400
错误,但是我想返回另一个页面.我该如何实现?
I want to handle the missing parameter case by not adding in required = false
. By default, 400
error is returned, but I want to return, let's say, a different page. How can I achieve this?
推荐答案
如果请求中不存在必需的@RequestParam
,Spring将抛出
If a required @RequestParam
is not present in the request, Spring will throw a MissingServletRequestParameterException
exception. You can define an @ExceptionHandler
in the same controller or in a @ControllerAdvice
to handle that exception:
@ExceptionHandler(MissingServletRequestParameterException.class)
public void handleMissingParams(MissingServletRequestParameterException ex) {
String name = ex.getParameterName();
System.out.println(name + " parameter is missing");
// Actual exception handling
}
我想返回另一个页面.我该如何实现?
I want to return let's say a different page. How to I achieve this?
Spring文档指出:
与标有
@RequestMapping
的标准控制器方法非常相似 批注,方法的参数和返回值@ExceptionHandler
方法可以灵活.例如, 可以在Servlet环境中访问HttpServletRequest
,并且 在Portlet环境中PortletRequest
. 返回类型可以是String
,它被解释为视图名称,一个ModelAndView
对象,一个ResponseEntity
,或者您也可以添加@ResponseBody
以使 用消息转换器转换并写入的方法返回值 响应流.
Much like standard controller methods annotated with a
@RequestMapping
annotation, the method arguments and return values of@ExceptionHandler
methods can be flexible. For example, theHttpServletRequest
can be accessed in Servlet environments and thePortletRequest
in Portlet environments. The return type can be aString
, which is interpreted as a view name, aModelAndView
object, aResponseEntity
, or you can also add the@ResponseBody
to have the method return value converted with message converters and written to the response stream.
这篇关于Java Spring-如何处理缺少的必需请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!