Java Spring - 如何处理缺少所需的请求参数

标签 java spring spring-mvc

考虑以下映射:

@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, the HttpServletRequest can be accessed in Servlet environments and the PortletRequest in Portlet environments. The return type can be a String, which is interpreted as a view name, a ModelAndView object, a ResponseEntity, 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/

相关文章:

java - 获取下一个有效日

java - SWT工具栏: how to remove blue highlight on first ToolItem?

spring - 文件上传在 Primefaces 中不起作用

java - Controller HttpServletRequest 语言环境没有改变

java - 在Spring框架中使用@RequestMapping时如何匹配通配符接受 header

java - Eclipse 将每个参数放在新行中,如何停止这种格式化

java - 以下响应的格式?

java - Spring 启动,maven : failing to run or package an application

java - 要求属性在模型中具有值,不允许为 null

spring - Spring BeanPostProcessor 究竟是如何工作的?