Java Spring-如何处理缺少的必需请求参数
问题内容:
考虑以下映射:
@RequestMapping(value = "/superDuperPage", method = RequestMethod.GET)
public String superDuperPage(@RequestParam(value = "someParameter", required = true) String parameter)
{
return "somePage";
}
我想通过 不 添加来处理参数丢失的情况required = false
。默认情况下,400
返回错误,但是我想返回另一个页面。我该如何实现?
问题答案:
如果@RequestParam
请求中没有要求,Spring将抛出MissingServletRequestParameterException
异常。您可以@ExceptionHandler
在同一控制器中或中定义@ControllerAdvice
来处理该异常:
@ExceptionHandler(MissingServletRequestParameterException.class)
public void handleMissingParams(MissingServletRequestParameterException ex) {
String name = ex.getParameterName();
System.out.println(name + " parameter is missing");
// Actual exception handling
}
我想返回另一个页面。我该如何实现?
如Spring文档所述:
与标有
@RequestMapping
注解的标准控制器方法非常相似,
方法的参数和方法的返回值@ExceptionHandler
可以很灵活。例如,
HttpServletRequest
可以在Servlet环境和PortletRequest
Portlet环境中访问。
返回类型可以是aString
,它被解释为视图名称,ModelAndView
对象,a
ResponseEntity
,或者您也可以添加@ResponseBody
以使方法返回值通过消息转换器转换并写入响应流。