考虑以下映射:
@RequestMapping(value = "/superDuperPage", method = RequestMethod.GET)
public String superDuperPage(@RequestParam(value = "someParameter", required = true) String parameter)
{
return "somePage";
}
我想通过 not 添加 required = false
来处理缺少参数的情况。默认情况下,返回 400
错误,但我想返回一个不同的页面。我怎样才能做到这一点?
最佳答案
如果请求中不存在所需的 @RequestParam
,Spring 将抛出 MissingServletRequestParameterException
异常(exception)。您可以在同一 Controller 或 @ControllerAdvice
中定义 @ExceptionHandler
来处理该异常:
@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 documentation状态:
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 - 如何处理缺少所需的请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37746428/