Java Spring-如何处理缺少的必需请求参数 [英] Java Spring - how to handle missing required request parameters

查看:886
本文介绍了Java Spring-如何处理缺少的必需请求参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下映射:

@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, 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-如何处理缺少的必需请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆